Smoothing the promise map

I am wondering how you are going to flatten the results from a map of Promise promises that are arrays. I have a function that Promise.maps over a set of values, which themselves are promises (to be resolved) and return an array. So I am returning something like: [[1, 2, 3], [1, 2, 3], etc.] I used lodash / underscore._flatten after, however, I'm sure there is a cleaner method ...

return Promise.map(list, function(item) {
  return new Promise(function(res, rej) {
    return res([1, 2, 3]);
  });
});

      

+3


source to share


1 answer


Not in bluebird flatMap

, you can .reduce

if you want to execute the results:

return Promise.map(list, function(item) {
    return Promise.resolve([1, 2, 3]); // shorter than constructor
}).reduce(function(prev, cur){
    return prev.concat(cur);
}, []);

      

Although lodash flatten will also work like:

return Promise.map(list, function(item) {
    return Promise.resolve([1, 2, 3]); // shorter than constructor
}).then(_.flatten);

      



You can also teach bluebird to do this (if you are the author of the library - see how to get a new copy without collisions):

Promise.prototype.flatMap = function(mapper, options){
    return this.then(function(val){ 
         return Promise.map(mapper, options).then(_.flatten);
    });
});

Promise.flatMap = function(val, mapper, options){
    Promise.resolve(val).flatMap(mapper, options);
});

      

What would you do:

return Promise.flatMap(list, function(){
     return Promise.resolve([1, 2, 3]);
});

      

+10


source







All Articles