我有一个从另一个网站请求数据的代码(获取链接),在我获取链接后,我将从这些链接中获取一些数据。所以,我正在尝试做两个请求。
下面是我编写的伪代码。
[first request to the site]
..fetch links and data
....fetch more data from the fetched links
[done]
[another function to fetch data from the links fetched]
..fetch data
[return fetch data]我正在尝试获得如下输出:
{
"chimchar" : {
"articles" : [{
"id": id,
"title": title,
"url": url
}]
}
}但是'url‘的值没有显示,我尝试将它登录到控制台,但’url‘的值是未定义的,并且在从.getHome函数发出所有请求之后才显示出来。
这是代码。
var cheerio = require('cheerio');
var requestify = require('requestify');
var _response;
/*
getHome
*/
exports.getHome = function(req, res) {
requestify.get('http://chimchar.com').then(function(response) {
var __response = processResponse(response);
res.send(__response);
});
}
/*
processResponse
*/
function processResponse(response) {
var id = 0;
var title, url;
_response = {
'chimchar': {
'articles': []
}
};
response.getBody();
$ = cheerio.load(response.body);
$('#scenesContainer .video_box').each(function() {
$(this).find('img, a').each(function(i, elem) {
if ($(this).is('img') && $(this).attr('style') == 'margin-top: 35px;')
title = $(this).attr('alt');
if ($(this).is('a') && $(this).attr('class') == 'link_block') {
fetchPage($(this).attr('href'), function(returnValue) {
url = returnValue;
console.log(url);
});
}
});
_response.chimchar.articles.push({
"id": id,
"title": title,
"url": url,
});
id = id + 1;
});
return _response;
}
var fetchPage = function(page, callback) {
console.log('fetchPage');
requestify.get('http://chimchar.com' + page).then(function(response) {
var r;
response.getBody();
$ = cheerio.load(response.body);
$('.play_video').each(function() {
$(this).find('a').each(function(i, elem) {
if ($(this).is('a') && $(this).text().indexOf('MP4') > -1) {
r = $(this).attr('href');
console.log(r);
}
});
});
console('fetchPage finished - ' + r);
callback(r);
});
};发布于 2014-07-15 18:49:22
我认为
return _response;在您的processResponse函数中获取url之前触发
我认为您需要使用异步,代码将如下所示
function processResponse(response, callback) {
async.each([items], function (item, cb) {
doSomething(item, function () {
//Make all operations with response
cb(null, true)
});
},
function (err, result) {
callback(_response)
})
}https://stackoverflow.com/questions/24751862
复制相似问题