javascript - 有没有办法在继续之前等待 promise ?

标签 javascript

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

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

我尝试过使用 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"
  }
]

最佳答案

您的代码有 3 个问题:

  1. getDetail 应该为 await 返回实际等待的 promise 。
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();

这是一个有效的 pen

关于javascript - 有没有办法在继续之前等待 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58727913/

相关文章:

java - IE 将 JAX-RS Web 服务的字符串响应视为文件

javascript - 在 JavaScript 中合并

javascript - 有没有办法对这个对象数组进行分组或减少

javascript - AngularJS ng-init 指令被分配了函数和 promise

javascript - 如何在 react-select 中将 props 传递给自定义组件

javascript - node.js - 将不同数据发送到不同客户端的良好实现是什么?

javascript - 如何将参数传递给函数本身就是参数的函数?

javascript - 仅当变量包含值时才创建包含变量的数组

javascript - 无法使 route.get 在 Node 中工作

javascript - 如何使滚动 jQuery 监听器适应 CSS 媒体查询? (Javascript/jQuery/Bootstrap )