如何在JavaScript中解开Promise的价值

时间:2019-03-05 05:34:34

标签: javascript promise

我有以下代码:

...
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中,我得到了承诺,但是如何获得生成的数组?

1 个答案:

答案 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);
})();