我有以下代码:
...
const array = nestings.map(async nesting =>
await Promise.all([
getFirstDataFromDB();
getSecondDataFromDB();
getThirdDataFromDB();
]);
.then([data1, data2, data3]) => ({data1: data1, data2: data2, data3: data3}))
.catch(error => console.log(error))
...
console.log(array); // Promise
在console.log中,我得到了承诺,但是如何获得生成的数组?
答案 0 :(得分:6)
您将需要两个 个Promise.all
-一个用于每个单独的项目,然后另一个Promise.all
。整个数组的Promise.all
解析后,您可以将.map
的结果转换为所需的对象数组:
const arrayOfProms = nestings.map(nesting => Promise.all([
getFirstDataFromDB(),
getSecondDataFromDB(),
getThirdDataFromDB()
]));
const arrOfData = await Promise.all(arrayOfProms);
const array = arrOfData.map(
([data1, data2, data3]) => ({data1: data1, data2: data2, data3: data3})
);
示例片段:
const getData = () => new Promise(res => setTimeout(res, 200, 'someval'));
const nestings = ['foo', 'bar', 'baz'];
(async () => {
const arrayOfProms = nestings.map(nesting => Promise.all([
getData(),
getData(),
getData()
]));
const arrOfData = await Promise.all(arrayOfProms);
const array = arrOfData.map(
([data1, data2, data3]) => ({data1: data1, data2: data2, data3: data3})
);
console.log(array);
})();