首页 > 解决方案 > 有没有办法在继续之前等待承诺?

问题描述

我有一些数据数组,并希望他们每个人都能获得一些信息。

我想在进程启动时记录控制台并在完成时记录数据,但结果给我的数据与初始化时相同。

我尝试过使用 async / await 但它没有按我的预期工作。

这是我的代码

const data = [
  {
    name: 'User 1',
    detail: 0
  },
  {
    name: 'User 2',
    detail: 0
  },
  {
    name: 'User 3',
    detail: 0
  }
];

function getDetail() {
  setTimeout(() =>  {
        return "Detail Test";
   }, 3000);
}

async function mapping() {
  await Promise.all(data.map(async (item) => {
    item.detail = await getDetail();
  }))
}


console.log("Start");
mapping();
console.log(data);

结果还是一样。

[
  {
    name: 'User 1',
    detail: 0
  },
  {
    name: 'User 2',
    detail: 0
  },
  {
    name: 'User 3',
    detail: 0
  }
]

我的期望

[
  {
    name: 'User 1',
    detail: "Detail Test"
  },
  {
    name: 'User 2',
    detail: "Detail Test"
  },
  {
    name: 'User 3',
    detail: "Detail Test"
  }
]

标签: javascript

解决方案


您的代码存在 3 个问题:

  1. getDetail应该返回一个await实际等待的承诺。
const getDetail = () => new Promise((resolve) => {
  setTimeout(() =>  {
        resolve("Detail Test");
   }, 3000);
}
  1. Array.map不修改原始数组,强烈推荐但为了回答您的问题:
async function mapping() {
  await Promise.all(data.map(async (item, i) => {
    data[i].detail = await getDetail();
  }))
}
  1. 最后,您需要等待映射以使更改生效:
async function run() {
  console.log("Start");
  await mapping();
  console.log(data);
};

run();

这是一支工作


推荐阅读