javascript - 如何将 Async.js everySeries 示例转换为 Bluebird Promises?

标签 javascript node.js asynchronous promise async.js

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

干杯
微开

最佳答案

我重新格式化并删除了注释,但这与您的异步代码具有相同的行为。关键是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')
});

关于javascript - 如何将 Async.js everySeries 示例转换为 Bluebird Promises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32121252/

相关文章:

javascript - IOS:如何检测用户在内容可编辑的 div 中更改 UIWebView 上的文本

javascript - 有人可以帮助我理解以下代码的输出吗?

javascript - JS 上的匿名函数

node.js - 从消息中获取图像 URL

node.js - 如何在 'nodejs'中找到请求参数

c# - 对使用异步调用的 MassTransit 消费者进行单元测试

javascript - 背景图片的高度和宽度适应每个屏幕尺寸

javascript - 如何在导入语句中使用模板文字?

python - 在 Tornado 中,如何查看在 PeriodicCallback 调用的协程中引发的异常?

c# - 等待和异步阻塞 UI