javascript - 如何在 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 问题,但仍然无法弄清楚。
解决方案
我很难准确理解你在问什么问题,但.map()
不是精通异步的。这意味着即使您将回调声明为async
,.map()
也不会对返回的承诺做任何事情,因此它不会在第一次迭代完成之前等待开始第二次迭代。因此,您最终会并行运行循环的所有迭代中的所有异步操作,并且它们可以以任何随机顺序完成。
如果你真的想按顺序运行它们,一个接一个,然后切换.map()
到一个for
循环,因为for
循环将在循环的第一次迭代中等待一个await
循环,然后再开始循环的第二次迭代,依此类推......
推荐阅读
- javascript - 组合一个对象的所有 forEach
- tensorflow - 我的 LSTM 模型陷入 0.5 准确度和 0.7 损失
- vue.js - 在编码方面,vuejs 和 nuxtjs 有什么相似之处?
- android - Jetpack Compose 将编码的字符串作为参数传递给 navController 会导致 IllegalArgumentException
- r - 在 R 中使用 grepl 减少嵌套的 if else 语句
- kotlin - 刷新惰性值
- python - 是否可以根据任务的最大内存使用量来改变 Celery 工作线程的并发性?
- java - 脚本外壳不返回所有输出消息
- javascript - 使用简单键盘的多语言支持
- html - 网格的模块属性之一存在问题