我有一系列多维的 promise 需要解决。如果我 console.log 结果,我可以查看数组,每个数组中都有一个 Promise 以及一个 [[PromiseStatus]] 和一个 [[PromiseValue]]。我如何获得 promise 值?
这是一段代码:
(resourcePromises 只是一个 promise 的多维数组)。
Promise.all(resourcePromises).then(function(values)
{
console.log(values);
});
然后变量值将保存多个数组,并且在每个数组中都有一个我试图从中获取值的 promise 列表。
最佳答案
听起来您需要在最深的级别运行 Promise.all
,然后是下一个最深的级别,依此类推,直到到达顶部。对于二维数组,这将是:
Promise.all(promises.map(Promise.all)).then(function(values) {
console.log(values);
});
如果您想进入任意深度,那么您需要为每个级别在 map
和 all
之间进行选择:
function deepAll(array) {
if (array instanceof Promise)
// Just in case...
return array;
else if (array.length == 0)
// The 'real' function will fail with an empty array and it's the same in both cases anyhow.
return [];
else if (Array.isArray(array[0]))
// There's another array level, so turn it into an array of promises.
return array.map(deepAll);
else
// This is an array of promises, and we already have a function for that case.
return Promise.all(array);
}
deepAll(promises).then(function(values) {
console.log(values);
});
关于javascript - 在多维数组中获取 Promise 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36517870/