Home > OS >  Node JS multliple promises chaining
Node JS multliple promises chaining

Time:06-23

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
    1. Emppty Array
    1. 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 ?

CodePudding user response:

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);
    }
};
  • Related