每个和callback

我正在使用请求和cheerio节点模块创build从网站获取一些数据。 我想获得一个项目列表,一旦这个列表完成,调用一个asynchronous函数:

request('http://myurl', function(req,res,data){ var $ = cheerio.load(data); var List = []; $('.myItems').each(function(i, element){ console.log( typeof $(this).text() ) List.push($(this).text()); }); for (var i=0; i < List.length; i++){ // make an asynchronous call to a API } }); 

我的问题是我如何等待列表完成,即我怎么能知道.each函数已遍历所有项目?

我可以用asynchronous吗?

谢谢

.eachfunction是同步的(参见源代码 )。 所以只要你在callback中没有任何asynchronous(这就是问题中的情况),你无需做任何事情:在接下来的一行中,循环将会完成。


如果您在循环中调用asynchronous函数,最简单最简单的解决scheme就是使用Promise库。

以顺序方式(以Bluebird为例):

 var p = Promise.resolve(); $('.myItems').each(function(i, element){ p = p.then(function(){ // do something with $(this).text() and return a promise }); }); p.then(function(){ // all asynchronous tasks are finished }); 

如果不需要顺序请求(这里是Q的例子):

 Q.allSettled($('.myItems').map(function(){ // return a promise })).then(function(){ // all asynchronous tasks are finished }); 

您可以使用asynchronous模块轻松处理这些types的asynchronous任务。

特别是async.each或async.eachLimit(如果需要并发> 1)或async.eachSeries(如果要一次一个地检查数组中的项目)。

我不得不承认,我还没有设法让DenysSéguret的解决scheme工作(在.each()循环中进行asynchronous调用) – “after”操作在.each()循环完成之前仍然发生,但是我发现了一个不同的方式,我希望它可以帮助某人:

 var Promises = require('bluebird'); request('http://myurl', function(req,res,data){ var $ = cheerio.load(data); var List = []; Promises // Use this to iterate serially .each($('.myItems').get(), function(el){ console.log( typeof $(el).text() ) List.push($(el).text()); }) // Use this if order of items is not important .map($('.myItems').get(), function(el){ console.log( typeof $(el).text() ) List.push($(el).text()); }, {concurrency:1}) // Control how many items are processed at a time // When all of the above are done, following code will be executed .then(function(){ for (var i=0; i < List.length; i++){ // make an asynchronous call to a API } }); }); 

在这个特定的代码示例中,它看起来像你可以做你的asynchronous调用,然后在映射函数,但你得到的要点…

地图: https : //github.com/petkaantonov/bluebird/blob/master/API.md#mapfunction-mapper–对象 – 选项 –

每个: https : //github.com/petkaantonov/bluebird/blob/master/API.md#eachfunction-iterator— promise