Bluebird Promise serial iteration, and resolve to modified array?

前端 未结 2 1542
无人及你
无人及你 2020-12-10 05:51

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..

相关标签:
2条回答
  • 2020-12-10 06:04

    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.

    0 讨论(0)
  • 2020-12-10 06:18

    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:

     function mapSeries(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

    0 讨论(0)
提交回复
热议问题