如何使用after和each连接在下划线js中创build一个同步循环

嗨我想创build一个使用下划线js的同步循环。 对于每个循环迭代,我进行一些进一步的asynchronous调用。 但是,我需要等到每个迭代调用完成之后才能继续下一个迭代。

这是可能的下划线JS? 如果是的话,怎么样? 有人可以提供一个例子吗?

_.( items ).each( function(item) { // make aync call and wait till done processItem(item, function callBack(data, err){ // success. ready to move to the next item. }); // need to wait till processItem is done. }); 

更新我解决了这个使用async.eachSeries方法。

  async.eachSeries( items, function( item, callback){ processItem(item, function callBack(data, err){ // Do the processing.... // success. ready to move to the next item. callback(); // the callback is used to flag success // andgo back to the next iteration }); }); 

你不能使用像下划线的.each()这样的同步循环结构,因为在进行下一次迭代之前,它不会等待asynchronous操作完成,而且也不能在单个线程化的世界中这样做像Javascript。

您将不得不使用专门支持asynchronous操作的循环结构。 有很多select – 你可以很容易地build立你自己的,或者在node.js中使用asynchronous库,或让承诺为你sorting。 下面是关于下划线中的一些asynchronous控制的文章:daemon.co.za/2012/04/simple-async-with-only-underscore。

以下是我使用的一种常见devise模式:

 function processData(items) { // works when items is an array-like data structure var index = 0; function next() { if (index < items.length) { // note, I switched the order of the arguments to your callback to be more "node-like" processItem(items[index], function(err, data) { // error handling goes here ++index; next(); } } } // start the first iteration next(); } 

对于为node.js预build的库, asynchronous库经常用于此目的。 它具有许多stream行的迭代方法,如.map() .each()等等的asynchronous版本。在你的情况下,我想你会在寻找.eachSeries()强制asynchronous操作​​一个接一个地运行(而不是并行)。


为了使用承诺, 蓝鸟承诺库有一个asynchronous的.each() ,当一个承诺解决时允许你在迭代器中使用asynchronous操作,但保持顺序执行,调用下一个迭代。

作为你的问题的答案:不,这不能用下划线来完成。 所有的项目将被处理,你没有办法处理arrays作为系列。

你可能想看看像async / mapSeries

Interesting Posts