首页 > 解决方案 > Node.js 承诺 .then() 不是序列

问题描述

它在 number1 完成之前运行 .then() number2。PS getConnectIn() 是承诺

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)})
 }

显示图片

标签: javascriptnode.jspromise

解决方案


你使用then错误的方式。在第一个then处理程序方法中,您没有返回任何内容,这就是 JS 引擎将then在链中继续运行的原因。将您的代码更新为:

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)
    })
}

查看MDN 页面以了解有关承诺链的更多信息。


推荐阅读