首页 > 解决方案 > 如何在 JavaScript 中迭代多个异步等待函数并链接在一起?

问题描述

我是 JavaScript 和 Node.js 的新手。我有以下代码:

  const populateSetup = async () => {
  token = await getToken();

  const promises = await constant.accounts.map(async (x) => {
    const accountId = await createAccountRequest(x.account);
    const peoid = await createPeopleRequests(x.people);
    const pid = await createProjectsRequests(x.project);

    return [accountId, pid, peoid];
  });

  const [accountId, pid, peoid] = await Promise.all(promises);
};

在上面,首先获取token并需要创建帐户,然后需要返回accountId来创建人员和项目。假设我有以下输入:

    exports.accounts = [
  { account: this.testAccountFirst, project: this.projectOne, people: this.testUserOne },
  { account: this.testAccountSecond, project: this.projectTwo, people: this.testUserTwo },
];

运行populateSetup()节点内环境后,我的结果是(不是控制台输出,而是以下输出populateSetup()

testAccountFirst has 1 people -> testUserOne
testAccountSecond has 2 projects and 1 user -> projectOne, projectTwo, testUserTwo

预期结果是:

testAccountFirst should have 1 project and 1 people -> projectOne, testUserOne
testAccountSecond should have 1 project and 1 people -> projectTwo, testUserTwo

这里的问题是第一个账户的accountId没有发送到projectsRequest。我不知道如何解决这个问题。我已经完成了这个Stackoverflow 问题,但仍然无法弄清楚。

标签: javascriptnode.js

解决方案


我很难准确理解你在问什么问题,但.map()不是精通异步的。这意味着即使您将回调声明为async.map()也不会对返回的承诺做任何事情,因此它不会在第一次迭代完成之前等待开始第二次迭代。因此,您最终会并行运行循环的所有迭代中的所有异步操作,并且它们可以以任何随机顺序完成。

如果你真的想按顺序运行它们,一个接一个,然后切换.map()到一个for循环,因为for循环将在循环的第一次迭代中等待一个await循环,然后再开始循环的第二次迭代,依此类推......


推荐阅读