我试图执行多个迭代函数,并且无法获取node.js异步类型的工作。如何在异步函数中等待请求方法
async.waterfall([
function (callback) {
// function gets amount of pages
},
function (amountOfPages, callback) {
//addes a url to each page
},
function (links, callback) {
//Now i need to go over each link , and extract info from that page
var tradelinks = [];
async.each(links, function (link, callback){
console.log("In loop : "+ link) // Until this part its doing all right , then it hangs on the request
request(link , function (error, response, body) {
//extract from page...
})
callback()
})
callback(null, tradelinks);
}
], function (err, result) {
console.log("Done")
console.log(result)
});
基本上它在正确的顺序前两个函数,那么它走遍了联系,并不会等待请求函数执行,所以即时得到结果中的一个空白阵列和done
标志,只有之后,它会打印从页面中提取的数据。
我的输出看起来像这样
Function 1 done
Function 2 done
In the async.each loop // for how many links there are
Done
[] //only after this point the data extracted from page appears
extracted data // for how many links there are
我的新用这种编程,和真的不知道如何从着手这儿过得知道这可与承诺或那样的事情要做,但是我似乎无法得到它的工作。
async.each()丢失它的完整的回调(这是瀑布迭代回调应该叫) –
尝试使用'cb',而不是'callback'在'each'循环。 'async'会认为瀑布步骤已经完成.. – Rayon
尝试过使用cb,没有工作。你是什么意思,因为错过了完整的回调? –