我正在尝试并行运行函数数组,当每个人都完成时,我想要对该结果进行处理。 我正在使用承诺。现在,我可以将所有函数放在一个数组中并且可以执行 Promise.all(函数数组) 但我有像
这样的数组[[promise1, promise2], [promise3,promise4], [promise5,promise6]],
每个承诺都是承诺的功能。 Promise参考文档说Promise.all中的参数应该是一个可迭代的对象,我的数组是可迭代的。 但这对我不起作用。我认为它正在执行[promise1,promise2]作为承诺而不是个人承诺。
任何人都可以帮助我如何实现它,还是有更好的方法?
答案 0 :(得分:17)
您还需要为每个数组项调用public IEnumerable<Employee> Get()
{
// There could be such a constraint as illustrated below.
// Note the Take(100), this is the constraint or restriction
return employees.Where(x => x.Department == "HR").Take(100);
}
:
Promise.all
或直接:
const promise4all = Promise.all(
promiseArray.map(function(innerPromiseArray) {
return Promise.all(innerPromiseArray);
})
);
这样,外部// Fix: Promise.all.bind is required because it seems like Promise.all
// implementation relies on "this"
const promise4All = Promise.all(promiseArray.map(Promise.all.bind(Promise)))
// or
// const promise4All = Promise.all(promiseArray.map(p => Promise.all(p)))
会在其他Promise.all
中获得分组的承诺:
Promise.all
答案 1 :(得分:8)
您可以在所有内部数组上使用Promise.all
,然后在外部数组上使用Promise.all(promiseArrArr.map(Promise.all, Promise)).then(arrArr => …)
来获取数组数组的承诺:
Promise.all
请注意double price = 52000;
String.format("$%,.2f", price);
接受一系列promise,而不是一系列promise返回函数。
答案 2 :(得分:5)
另一个选择是将数组数组展平为单个数组,然后可以直接使用Promise.all()
。直接来自example on MDN,你可以使用.reduce()
和.concat()
这样做:
var promises = [[promise1, promise2], [promise3,promise4], [promise5,promise6]];
Promise.all(promises.reduce(function(a, b) { return a.concat(b); }, []))
.then(function(results) {
// all done here
// results are in a flattened array
});
此解决方案允许原始promises数组包含单个promise或promises数组或两者的任意组合。它以这种方式灵活,它在单个扁平化结果数组中提供结果,这些结果与原始承诺的顺序相同,但是被展平为单个数组。因为Promise.all()
要求你传递一个数组,所以这里提出的其他解决方案要求输入是一个严格的数组数组 - 该数组不能只在promises数组中有任何简单的承诺。这种解决方案以这种方式更灵活,并且可以接受任何类型的输入。
例如,如果输入恰好是这样的话,这将正常工作:
var promises = [promise1, promise2, [promise3, promise4], [promise5, promise6]];
参见工作演示:https://jsfiddle.net/jfriend00/dLsktyyn/
或者您可能会发现将flatten()
函数用于其他用途很有用:
function flatten(arr) {
return arr.reduce(function(a, b) { return a.concat(b); }, []);
}
var promises = [[promise1, promise2], [promise3,promise4], [promise5,promise6]];
Promise.all(flatten(promises)).then(function(results) {
// all done here
});
答案 3 :(得分:0)
您可以使用此方法:
instance (X a, Enum a, Enum b, X b) => X (a,b) where
r ((a,b), (c,d)) = r' ((a,b), (c,d)) b
where
r' ((a, b), (c,d)) b'
| a == c && b == d = [(a,b)]
| b < d = (a,b) : (r' ((a, succ b), (c, d)) b')
| otherwise = (a,b) : (r' ((succ a, b'), (c,d)) b')
答案 4 :(得分:0)
如果子阵列的数量固定,我建议使用以下简单解决方案:
const balancePromises = [...];
const symbolPromises = [...];
const [balances, symbols] = await Promise.all([
Promise.all(balancePromises),
Promise.all(symbolPromises)
]);
答案 5 :(得分:0)
如果您希望展平多阵列并遵守所有承诺,则可以执行以下操作:
const promiseAll = Promise.all(promiseArray.flat());