Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening a Promise map

I'm curious how you go about flattening the results from a Promise map of promises that are arrays. I have a function that Promise.maps over a set of values that they themselves are promises (needing to be resolved) and are returning an array. So, I get back something like: [ [1, 2, 3], [1, 2, 3], etc. ] I've been using the 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]);
  });
});
like image 379
Farhad Ghayour Avatar asked Jun 12 '15 17:06

Farhad Ghayour


1 Answers

We don't have a flatMap in bluebird, you can .reduce if you'd like in order to concat 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 a lodash flatten would also work as:

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

It's also possible to teach bluebird to do this (if you're a library author - see how to get a fresh copy for no 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);
});

Which would let you do:

return Promise.flatMap(list, function(){
     return Promise.resolve([1, 2, 3]);
});
like image 78
Benjamin Gruenbaum Avatar answered Oct 09 '22 10:10

Benjamin Gruenbaum