I'm new in JavaScript and Node.js. I have the following code:
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);
};
In the above, token is first fetched and is required to create account and then accountId returned is required to create people and projects. Let's say I have the following input:
exports.accounts = [
{ account: this.testAccountFirst, project: this.projectOne, people: this.testUserOne },
{ account: this.testAccountSecond, project: this.projectTwo, people: this.testUserTwo },
];
After running the populateSetup() in node environment my result is (not the console output but the output of the populateSetup():
testAccountFirst has 1 people -> testUserOne
testAccountSecond has 2 projects and 1 user -> projectOne, projectTwo, testUserTwo
expected result is:
testAccountFirst should have 1 project and 1 people -> projectOne, testUserOne
testAccountSecond should have 1 project and 1 people -> projectTwo, testUserTwo
The problem here is that the accountId of first account is not sent to the projectsRequest. I don't know how to resolve this. I have gone through this Stackoverflow question but still couldn't figure out.
await promise.all()is an array where each element in the array is[accountId, pid, peoid]. Also.map()runs all your async operations in parallel. The 2nd iteration doesn't start until the first one is done. If you want to run them one iteration at a time, use a regularforloop.for loopworked for me.console.log(accountId, pid, peoid);would ever printtestAccountFirst, testUserOne, in any situation. It will always print 3 values, space separated, even if one of them isundefined. Never 4, and no commas. Please, update your question so that next person reading it will not get confused.