javascript - NodeJS 无法异步发出 GET 请求

标签 javascript node.js asynchronous

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

我的问题是处理它们。对于每个 url,我都会执行 GET 请求来获取正文并查找其中的图像元素。我希望将图像 url 作为 GET 参数传递给第 3 方 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("_=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=__=_=_=_=_=_=_");
});

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

关于javascript - NodeJS 无法异步发出 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589464/

相关文章:

javascript - 使用 Twitter/typeahead.js 在 SELECT 查询中合并 SQL LIKE

javascript - Node/express 如何在 req.headers 上进行 .split

node.js - 使用 Jest(和 mockgoose)测试 Node.js API

ajax - 在不执行多个请求的情况下多次订阅 rxjs Observer

javascript - 扩展JS 4.2 : Checkbox model selection issue

javascript - 使用 jQuery 按 id 隐藏 div 在 Greasemonkey 中不起作用?

javascript - 如何在 express.js 中抛出 404 错误?

javascript - 使用 multer 上传多个文件?

python - 在此异步设置中,我在哪里捕获 KeyboardInterrupt 异常

c# - 了解 C# 中的异步和等待