How can I chain promises sequentially using bluebirdjs?

Promise.all () does not guarantee that promises will be resolved in order. How can I do that?

+6
source share
2 answers

Since you are using Bluebird JS, this can be done in a simple way.

In version 2.0, Bluebird introduced the Promise.each method, which does this because the loop loop is then quite simple, but since it is so common and requested from time to time, 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) }); 

Which gives the same result as another answer, with only fewer lines of code, and also allows Bluebird to perform iteration optimization.

+7
source

What confused me the most was that the asynchronous connection function should return a function that returns a promise. Here is an example:

 function setTimeoutPromise(ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); } function foo(item, ms) { return function() { return setTimeoutPromise(ms).then(function () { console.log(item); }); }; } var items = ['one', 'two', 'three']; function bar() { var chain = Promise.resolve(); items.forEach(function (el, i) { chain = chain.then(foo(el, (items.length - i)*1000)); }); return chain; } bar().then(function () { console.log('done'); }); 

Note that foo returns a function that returns a promise. foo () makes no direct promise.

Watch Live Demo

0
source

Source: https://habr.com/ru/post/973892/


All Articles