如何使用after和each结合在下划线js中创建同步循环

时间:2014-09-18 16:48:14

标签: node.js underscore.js each synchronous

您好我尝试使用下划线js创建同步循环。对于每个循环迭代,我进行一些进一步的异步调用。但是,我需要等到每次迭代调用完成后再继续下一次迭代。

下划线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
      });
 });

2 个答案:

答案 0 :(得分:3)

您不能使用同步循环结构,例如下划线.each(),因为它不会等到异步操作完成后再进行下一次迭代,它可以& #39;在像Javascript这样的单线程世界中这样做。

您必须使用专门支持异步操作的循环结构。有很多可供选择 - 您可以轻松地构建自己的或者在node.js中使用异步库,或者让promises为您排序。这是一篇关于下划线中某些异步控件的文章:daemon.co.za/2012/04/simple-async-with-only-underscore。

这是我使用的一种常见设计模式:

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的预构建库,async library经常用于此目的。它具有许多流行方法的异步版本,用于迭代集合,例如.map().each().reduce()等等。在您的情况下,我认为您是&#dd; d正在寻找.eachSeries()来强制异步操作​​一个接一个地运行(而不是并行)。


对于使用promises,Bluebird promise library具有异步功能.each(),当解析promise时允许您在迭代器中使用异步操作,但保持顺序执行,从而调用下一次迭代。

答案 1 :(得分:1)

作为您问题的答案:不,这不能用下划线来完成。所有项目都将被处理,您无法将阵列作为系列进行处理。

您可能希望查看类似async/mapSeries

的内容