Flattening a Promise map

谁说我不能喝 提交于 2019-12-10 14:09:12

问题


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]);
  });
});

回答1:


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]);
});


来源:https://stackoverflow.com/questions/30809197/flattening-a-promise-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!