I have node JS api server and I’m having issues with correct chaining of the Promises:
app.post( "/api/tasks", async function (_req, res) { const newArray = [{ MyTasks: [] }]; const getOne = async (owner, taskID) => { return await getOneDocument(owner, taskID).then((result) => { console.log("get one doc", result); return result; }); }; // first promise let toApproveTasks = await getToApproveTasks(_req.body.userID); console.log("1", toApproveTasks); // loop trough the result of 1st promise and run async function for each const arrayToDoc = async (array) => { array.TasksToApprove.forEach(async (element) => { let objToPush = await getOne(element.Owner, element.TaskID); console.log("1.5", objToPush); newArray.MyTasks.push(objToPush); }); }; // second promise await arrayToDoc(toApproveTasks); console.log("2", newArray); // third promise let finalResult = await parseCosmosOutput(newArray); console.log("3", finalResult); res.status(200).send(finalResult); } );
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
const arrayToDoc = async (array) => { for(let element of array.TasksToApprove){ let objToPush = await getOne(element.Owner, element.TaskID); console.log("1.5", objToPush); newArray.MyTasks.push(objToPush); } };