【问题标题】:how to convert Async.js eachSeries example to Bluebird Promises?如何将 Async.js eachSeries 示例转换为 Bluebird Promises?
【发布时间】:2015-11-14 06:33:13
【问题描述】:

我正在研究 Promises,想知道是否有人熟悉 Async.js 可以演示如何使用 Bluebird Promise 执行以下操作。这是我能想到的用于演示 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...');
        }
    }
);

干杯
半开

【问题讨论】:

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


    【解决方案1】:

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

    Promise.delay 本质上是对setTimeout 的简单包装。

    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')
    });
    

    【讨论】:

      猜你喜欢
      • 2021-03-04
      • 2016-09-25
      • 1970-01-01
      • 2015-04-17
      • 2015-10-19
      • 2020-02-13
      • 2017-03-07
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多