javascript - 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)})
}
解决方案
你使用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 页面以了解有关承诺链的更多信息。
推荐阅读
- reactjs - React 中 npm 包的声明文件错误
- java - 找到除以所有数组元素的最小整数个数 >=2
- python - 如何在 python 中使用 selenium 定位父元素中的子元素?
- r - pivot_wider 在同一行上组合信息
- curl - 爬网时避免沉洞/恶意域
- search - 具有不同分析器的多个字段的 Solr 默认搜索字段
- java - 使用 lambda java 查找最大值
- docker - docker容器无法在vm上连接到互联网
- flutter - 当时我尝试使用火焰引擎加载base64图像时出现以下错误。我用火焰:^0.27.0
- android - 单击按钮时没有任何动作