展平承诺图 [英] Flattening a Promise map
问题描述
我很好奇您如何将Promise承诺图数组中的结果展平.我有一个Promise.maps函数,它们映射一组它们本身是promise(需要解析)的值,并返回一个数组.因此,我得到类似[[1、2、3],[1、2、3]等的信息.]之后,我一直在使用lodash/下划线._flatten,但是我确定有一个更清洁的方法.
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]);
});
});
推荐答案
我们在bluebird中没有flatMap
,如果愿意,可以使用.reduce
来确认结果:
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);
}, []);
尽管lodash拼合也可以用作:
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);
});
哪个会让你做:
return Promise.flatMap(list, function(){
return Promise.resolve([1, 2, 3]);
});
这篇关于展平承诺图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!