Skip to content Skip to sidebar Skip to footer

Bluebird Promise Serial Iteration, And Resolve To Modified Array?

I have this promise that creates a new Item document if it's not found in the db, and then stores it in a previously created Collection document.. The Collection document is the fi

Solution 1:

The .each function will not change the value that is passed through the chain:

I simplified your code, as input I assume:

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

For your code:

Promise.each(items, function(element) {
    return element+'.';
    //return Promise.resolve(element+'.');
})
.then(function(allItems) {
    console.dir(allItems);
});

The result will still be ['one','two'] because this are resolved values of the array items. The returned value within the each does not influence the content of the value passed to the chained then.

The .map function on the other hand will have this effect:

Promise.map(items, function(element) {
    return element+'.';
    //return Promise.resolve(element+'.');
})
.then(function(allItems) {
    console.dir(allItems);
});

Here the return value value will be used to create a new array which will then be passed to the then. Here the result would be ['one.','two.'].

The two allItems appearing in your code are different objects.

EDIT For serially iteration with mapping I would write a helper function like this:

functionmapSeries(things, fn) {
     var results = [];
     return Promise.each(things, function(value, index, length) {
         var ret = fn(value, index, length);
         results.push(ret);
         return ret;
     }).thenReturn(results).all();
 }

Source: Implement Promise.series

Solution 2:

Bluebird now natively implements a mapSeries, see http://bluebirdjs.com/docs/api/promise.mapseries.html

It also looks like Promise.each still returns the original array unfortunately in v3.x.x.

Post a Comment for "Bluebird Promise Serial Iteration, And Resolve To Modified Array?"