我是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/