简体   繁体   English

Node.js 承诺 .then() 不是序列

[英]Node.js promise .then() not sequence

it's run .then() number2 before number1 done.它在 number1 完成之前运行 .then() number2。 PS getConnectIn() is promise 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)}) }

display picture显示图片

You are using then in wrong way.您正在以错误的方式使用then In first then handler method you are not returning anything which is why JS engine will continue running next then in the chain.在第一then处理方法不必返回任何这就是为什么JS引擎将继续下一个运行then在链。 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.查看MDN 页面以了解有关承诺链的更多信息。

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.基本上 1 然后首先调用,但你再次调用异步方法(connector.query),这需要时间和控制传递到下一个调用,然后 setTimeout 将执行过程传递给 next ,要么在调用 setTimeout 时返回新的承诺,要么在异步连接器之后使用第二个。像这样的 query() 方法。 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)}
                     }
                  });
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM