【发布时间】:2019-08-16 23:00:22
【问题描述】:
我是 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 question,但仍然无法弄清楚。
【问题讨论】:
-
您的
await promise.all()是一个数组,其中数组中的每个元素都是[accountId, pid, peoid]。.map()也并行运行所有异步操作。直到第一次迭代完成后,第二次迭代才开始。如果您想一次运行它们一次迭代,请使用常规的for循环。 -
感谢 @jfriend00 使用
for loop为我工作。 -
虽然答案是正确的并且 for-loop 是解决方案之一,但我很难相信
console.log(accountId, pid, peoid);在任何情况下都会打印testAccountFirst, testUserOne。即使其中一个是undefined,它将始终打印 3 个值,空格分隔。从来没有 4,也没有逗号。请更新您的问题,以便下一个阅读它的人不会感到困惑。 -
@AlexPakka - 编辑了我的问题,对此感到抱歉
标签: javascript node.js