Home > Software engineering >  Run promises sequentially in node.js
Run promises sequentially in node.js

Time:12-09

I'm still figuring node.js and promises out.

There's an area in my code where I would like my sql statements to run sequentially.

I would like one sql statement to run once one sql statement is done. I'm not sure if I am implementing promises properly.

one of the sql statements:

 var selectbotagentstoadd=new Promise((resolve,reject)=>{
        var sql='SELECT tbltestbotagentstoadd.AgentID FROM tbltestbotagentstoadd WHERE tbltestbotagentstoadd.IDNumber=? AND tbltestbotagentstoadd.MSISDN=?;'
        DB.query(sql,[agentidpassnum,agentnumber],function(err,results){
            if (err){
                    return reject(err);
            }; 
            return resolve(results);
        });
       })

the promise statement:

await insertbotagentstoadd.then(()=>{
   console.log("done with one");
})
.then(()=>{ selectbotagentstoadd.then((results)=>
{
        AgenttoaddIDStore=[];
       results.forEach(agent=>{
          AgenttoaddIDStore.push({
           AgentID:agent.AgentID
       });
        ctx.session.tempAgentID=agent.AgentID
       });
console.log("agent ID: " ctx.session.tempAgentID);
console.log("done with two");
})})
.then((results)=>{insertcctblricaagents
console.log("done with three");
})
.then((results)=>{selectcctblricaagents.then((result)=>{
    console.log(result);
            AgentnewIDStore=[];
            result.forEach(agent=>{
                AgentnewIDStore.push({
                AgentID:agent.AgentID
            })
            ctx.session.AgentID=agent.AgentID
            })
            console.log("cctblricaagents agent ID: "  ctx.session.AgentID);
            console.log("done with four");
})})
.then(insertcctblricaagentsnum.then((result)=>{
console.log("done with five");
}))
.then(selectcctblricaagentsnum.then((result)=>{
    console.log(result)
    AgentIDStore=[];
    result.forEach(agent=>{
    AgentIDStore.push({
        AgentID:agent.AgentID,
        MainNumber:agent.MainNumber,
    })
    ctx.session.AgentID=agent.AgentID
    ctx.session.agentnumber=agent.MainNumber
    })
    console.log("cctblricaagentsnum agent ID: "  ctx.session.AgentID);
    console.log("done with six");
}))
.then(insertcctblintblbotagents.then((result)=>{
    console.log("done with seven");
}));

The results I get from the terminal:

Agent number: 27815567777
done with one
done with three
agent ID: 89
done with two
[]
cctblricaagents agent ID: null
done with four

CodePudding user response:

If you properly return the promises in each of the then blocks, it should execute sequentially.

simplifying your code, for ex:

await insertbotagentstoadd
  .then(() => {
    console.log("done with one");
  })
  .then(() => selectbotagentstoadd)
  .then((res) => {
    console.log("done with two");
    return res;
  })
  .then((results) => insertcctblricaagents)
  .then((res) => {
    console.log("done with three");
    return res;
  })
  .then((results) => selectcctblricaagents)
  .then((res) => {
    console.log("done with four");
    return res;
  })
  .then(() => insertcctblricaagentsnum)
  .then((res) => {
    console.log("done with five");
    return res;
  })
  .then(() => selectcctblricaagentsnum)
  .then((res) => {
    console.log("done with six");
    return res;
  })
  .then(() => insertcctblintblbotagents)
  .then((res) => {
    console.log("done with seven");
    return res;
  });

Edit:

How it will look with your calculation included:

await insertbotagentstoadd
  .then(() => {
    console.log("done with one");
  })
  .then(() => selectbotagentstoadd)
  .then((results) => {
    AgenttoaddIDStore = [];
    results.forEach((agent) => {
      AgenttoaddIDStore.push({
        AgentID: agent.AgentID,
      });
      ctx.session.tempAgentID = agent.AgentID;
    });
    return AgenttoaddIDStore;
  })
  .then((res) => {
    console.log("done with two");
    return res;
  })
  .then((results) => insertcctblricaagents)
  .then((res) => {
    console.log("done with three");
    return res;
  })
  .then((results) => selectcctblricaagents)
  .then((result) => {
    AgentnewIDStore = [];
    result.forEach((agent) => {
      AgentnewIDStore.push({
        AgentID: agent.AgentID,
      });
      ctx.session.AgentID = agent.AgentID;
    });
    return AgentnewIDStore;
  })
  .then((res) => {
    console.log("done with four");
    return res;
  });

CodePudding user response:

It looks like you are using the await keyword with the then method of a promise. This is not the correct way to use await with promises. keyword await only used inside async function. because the then method called asynchronously you should need to make your function a

like:

      async function runSqlStatements() {
     // Run the first SQL statement and wait for it to 
      //complete
      await insertbotagentstoadd;
        console.log('Done with first SQL statement');

      // Run the second SQL statement and wait for it to 
       //complete
       const results = await selectbotagentstoadd;
     console.log('Done with second SQL statement', 
       results);

         // Run the third SQL statement and wait for iT 
         //to complete
       await insertcctblricaagents;
       console.log('Done with third SQL statement');
     }

In your code, you should use the same method to run your SQL statements sequentially and await each one. This will ensure that each statement is executed in order and you can use the results of each statement in the next step of your code.

  • Related