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]);
});
});
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]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With