如何使用 bluebirdjs 按顺序链接承诺? [英] How can I sequentially chain promises using bluebirdjs?

查看:15
本文介绍了如何使用 bluebirdjs 按顺序链接承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Promise.all() 不保证承诺会按顺序解决.这怎么办?

Promise.all() doesn't guarantee that promises will be resolved in order. How can this be done?

推荐答案

由于您使用的是 Bluebird JS,这实际上可以通过简单的方式完成.

Since you're using Bluebird JS, this can be actually done in a simple way.

在 2.0 版本中,Bluebird 引入了执行此操作的 Promise.each 方法,因为循环 then 非常简单,但由于它是如此常见并且一次又一次地被请求,因此最终将其添加为自己的方法.

In version 2.0, Bluebird introduced the Promise.each method that does this, for looping a then is simple enough, but since it is so common and got requested time after time eventually it was added as its own method.

function foo(item, ms){ // note bluebird has a delay method
    return Promise.delay(ms, item).then(console.log.bind(console))
}

var items = ['one', 'two', 'three'];

Promise.each(items, function(item, i){
    return foo(item, (items.length - i) * 1000)
});

产生与另一个答案相同的结果,只是代码行更少,并且还让 Bluebird 对迭代执行优化.

Which produces the same result as the other answer, only with less lines of code and it also lets Bluebird perform optimizations on the iteration.

这篇关于如何使用 bluebirdjs 按顺序链接承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆