我正在尝试在node.js中执行以下代码: -
var i = 3
var p = Promise.resolve(i)
while (i > 0) {
(i => {
p = p.then(() => {
return new Promise((resolve) => {
let query1=new Promise(function(resolve,reject){
db.query(
"select * from users limit 1;",function(err,order){
if(err){
reject(err)
}
if(order){
if(order.length==0){
reject('No order found')
}else{
resolve(order)
}
}
})
})
query1.then(function(userdata){
if (userdata) {
console.log("query 1 start");
let query2=new Promise(function(resolve,reject){
db.query(
"select * from users limit 1;",function(err,order){
if(err){
reject(err)
}
if(order){
if(order.length==0){
reject('No order found')
}else{
resolve(order)
}
}
})
})
query2.then(function(userdata){
if (userdata) {
console.log("query 2 start");
i--;
return true;
}
})
.catch(function(err){
if (err) {
console.log("error");
}
})
return true;
}
})
.catch(function(err){
if (err) {
console.log("error");
}
})
})
})
})(i)
// i--
}
p = p.then(data => console.log('execution ends'))
执行时,会打印以下内容: -
query 1 start
query 2 start
当query2执行时,它停留在while循环之间。但是,我想使用while循环执行此代码3次,我的预期输出将如下所示: -
query 1 start
query 2 start
query 1 start
query 2 start
query 1 start
query 2 start
execution ends
所以任何人都知道如何在query2成功执行后再次启动代码执行?