NodeJS无法异步发出GET请求

时间:2013-12-14 23:29:40

标签: javascript node.js asynchronous

我是Nodejs和异步编程的新手。我在异步函数中执行GET请求时遇到问题。在这里,我发布了整个代码。我试图拉出所有Urls的列表,将它们添加到列表中并将列表发送到另一个函数。

我的问题在于处理它们。每个URL的Inturn我正在执行GET请求以获取正文并在其中查找图像元素。我希望将Image url传递给第三方api作为GET参数。我无法执行GET请求,因为控件似乎根本没有到达那里。

var async = require("async"),
request = require("request"),
cheerio = require("cheerio");


async.waterfall([

function(callback) {
    var url = "someSourceUrl";
    var linkList = [];
    request(url, function(err, resp, body) {
        var $ = cheerio.load(body);
        $('.list_more li').each(function() {
            //Find all urls and add them to a list
            $(this).find('a').each(function() {
                linkList.push($(this).attr('href'));
            });
        });
        callback(null, linkList);
    });
},


//pass all the links as a list to callback
function(liksListFetched, callback) {
    for (var i in liksListFetched) {
        callback(null, liksListFetched[i]);
    }
}],

//***********My problem is with the below code**************
function(err, curUrl) {
    var cuResp = "";
    console.log("Currently Processing Url : " + curUrl);

    request(curUrl, function(err, resp, body) {

        var $ = cheerio.load(body);
        var article = $("article");
        var articleImage = article.find("figure").children('img').attr('src');
        var responseGrabbed = "API response : ";
        //check if there is an IMG element
        if (articleImage === undefined) {
            console.log("No Image Found.");
            articleImage = 'none';
        }
        else {
            //if there is an img element, pass this image url to an API,
            //So do a GET call by passing imageUrl to the API as a GET param
            request("http://apiurl.tld?imageurl=" + articleImage, function(error, response, resp) {             //code doesn't seem to reach here 
                I would like to grab the response and concatenate it to the responseGrabbed var.
                console.log(resp);
                responseGrabbed += resp;
            });
        }
        console.log(responseGrabbed);// api response never gets concatenated :(
        console.log("_=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=_");
        process.exit(0);
    });
});

我很感激,如果有人能帮我理解根本原因。提前谢谢。

1 个答案:

答案 0 :(得分:3)

request()是异步的,所以当您在控制台中记录字符串时,该字符串尚未构建,您必须在回调中执行控制台日志:

request("http://apiurl.tld?imageurl=" + articleImage, function(error, response, resp) {                             
    responseGrabbed += resp;
    console.log(responseGrabbed);// api response never gets concatenated :(
    console.log("_=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=_");
});

终止流程也是如此,这应该在所有请求完成后完成