I have node JS api server and I’m having issues with correct chaining of the Promises:
JavaScript
x
35
35
1
app.post(
2
"/api/tasks",
3
async function (_req, res) {
4
5
const newArray = [{ MyTasks: [] }];
6
const getOne = async (owner, taskID) => {
7
return await getOneDocument(owner, taskID).then((result) => {
8
console.log("get one doc", result);
9
return result;
10
});
11
};
12
// first promise
13
let toApproveTasks = await getToApproveTasks(_req.body.userID);
14
console.log("1", toApproveTasks);
15
16
// loop trough the result of 1st promise and run async function for each
17
const arrayToDoc = async (array) => {
18
array.TasksToApprove.forEach(async (element) => {
19
let objToPush = await getOne(element.Owner, element.TaskID);
20
console.log("1.5", objToPush);
21
newArray.MyTasks.push(objToPush);
22
});
23
};
24
// second promise
25
await arrayToDoc(toApproveTasks);
26
console.log("2", newArray);
27
// third promise
28
let finalResult = await parseCosmosOutput(newArray);
29
console.log("3", finalResult);
30
31
res.status(200).send(finalResult);
32
}
33
);
34
35
What I get in console is :
- 1 [Object] – all good
-
- Emppty Array
-
- Empty Array
- get one doc {object} – all good
- 1.5 {object} – all good
How would I make sure when I loop over result of 1st promise my code awaits async function and pushes to newArray results ?
Advertisement
Answer
Use For..of instead of forEach inside arrayToDoc function
E.g
JavaScript
1
8
1
const arrayToDoc = async (array) => {
2
for(let element of array.TasksToApprove){
3
let objToPush = await getOne(element.Owner, element.TaskID);
4
console.log("1.5", objToPush);
5
newArray.MyTasks.push(objToPush);
6
}
7
};
8