winny
winny

Reputation: 5

Node.js promise .then() not sequence

it's run .then() number2 before number1 done. P.S. getConnectIn() is promise

function query(sql){
            var data = [555,555];
            getConnectIn()
               .then((check_connect)=>{   //then 1
                 if(check_connect){
                   connector.query(sql,function(err,result,fields){
                            data = result;
                      });
                  setTimeout(()=>{console.log("data before>",data);},1000);
                 }
              })
              .then(()=>{  //then 2
                console.log("data after>",data);
              })
              .catch((err)=>{console.log("error >",err)})
 }

display picture

Upvotes: 0

Views: 183

Answers (2)

Dipen Shah
Dipen Shah

Reputation: 26085

You are using then in wrong way. In first then handler method you are not returning anything which is why JS engine will continue running next then in the chain. Update your code to:

function query(sql) {
  var data = [555, 555];
  getConnectIn()
    .then((check_connect) => { //then 1
      if (check_connect) {
        return new Promise((resolve, reject) => {
          connector.query(sql, function(err, result, fields) {
            If (err) { 
              reject(err);
            } else {
              resolve(result);
            }
          });
        });
      }
    })
    .then(result => { //then 2
      // now you can access result here!
      console.log("data after>", data);
    })
    .catch((err) => {
      console.log("error >", err)
    })
}

Take a look at MDN page to learn more about promise chaining.

Upvotes: 1

user11475999
user11475999

Reputation:

Basically 1 then call first but you call async method again (connector.query) which takes time and control pass to next call and then setTimeout pass execution process to next , either return new promise when call setTimeout or Use second then after your async connector.query() method like this. here you don't need timeout also

function query(sql){
                var data = [555,555];
                getConnectIn()
                   .then((check_connect)=>{   //then 1
                     if(check_connect){
                       connector.query(sql,function(err,result,fields){
                               // data = result;
                          }).then((rslt)=>{  //then 2
                    console.log("data after>",rslt);
                        })
                  .catch((err)=>{console.log("error >",err)}
                     }
                  });
     }

Upvotes: 0

Related Questions