NodeJS无法异步发出GET请求

NodeJS unable to make a GET request asynchronously

本文关键字:GET 请求 异步 NodeJS      更新时间:2023-09-26

我是Nodejs和异步编程的新手。我在异步函数中执行GET请求时遇到问题。我在这里发布整个代码。我正在尝试提取所有Url的列表,将它们添加到列表中,并将列表发送给另一个函数进行处理。

我的问题是处理它们。Inturn对于每个url,我正在执行一个GET请求,以获取正文并在其中查找图像元素。我希望将图像url作为GET参数传递给第三方api。我无法执行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);
    });
});

如果有人能帮助我了解根本原因,我将不胜感激。提前谢谢。

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

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

终止过程也是如此,应该在所有请求都完成

时完成