如何将Async.js eachSeries示例转换为Bluebird Promises?

时间:2015-08-20 14:40:45

标签: javascript node.js asynchronous promise async.js

我正在调查Promises,并想知道是否有人熟悉Async.js可以演示如何使用Bluebird承诺执行以下操作。这是我能想到的最简单直接的例子来演示Async.js eachSeries。 对于不熟悉Async.js的人来说,这个例子在每个数组元素上运行相同的进程,以串行方式运行(一个接一个而不是并行运行),然后在所有异步操作完成后执行代码。

var async = require('async');

var items = [0,1,2,3,4,5,6,7,8,9]; // this is to simulate an array of items to process

async.eachSeries(items,
    function(item, callback){
        console.log('start processing item:',item);
        //simulate some async process like a db CRUD or http call...
        var randomExecutionTime = Math.random() * 2000;
        setTimeout(function(index){
                        //this code runs when the async process is done
                        console.log('async Operation Finished. item:',index);
                      callback(); //call the next item function
                    },randomExecutionTime,item);
    },
    function(err){
        if(err){
            console.log('Got an error')
        }else{
            console.log('All tasks are done now...');
        }
    }
);

干杯
微开

1 个答案:

答案 0 :(得分:4)

我重新格式化并删除了评论,但这与您的async代码具有相同的行为。关键是Promise.each,它是连续工作的。请注意Promise.each解析为原始数组。也就是说,如果你在传递给最终then的函数中接受一个参数,它将获得[0,1,2,3,4,5,6,7,8,9]

Promise.delaysetTimeout的简单包装,基本上是。

var Promise = require('bluebird');

var items = [0,1,2,3,4,5,6,7,8,9];

Promise.each(items, function(item) {
  console.log('start processing item:',item);
  var randomExecutionTime = Math.random() * 2000;
  return Promise.delay(randomExecutionTime)
  .then(function() {
    console.log('async Operation Finished. item:', item);
  });
}).then(function() {
  console.log('All tasks are done now...');
}).catch(function() {
  console.log('Got an error')
});