我在循环中有一系列 if 语句,如下所示:
for( var i = 0; i < results_list.length; i++){
find = await results_list[i];
//result 1
if (find.Process == "one") {
await stored_proc(38, find.Num, find.Status)
}
//result 2
if(find.Process == "two") {
await stored_proc(37, find.Num, find.Status)
}
//result 3
if(find.Process == "three") {
await stored_proc(39, find.Num, find.Status)
}
}
我的问题是它同步运行所有这些,导致我的存储过程自行出错。如何确保每个 if
语句在运行之前等待前一个语句完成?
了解每个 if
语句并不总是运行也很重要,例如在我的代码运行一次时 //result 2
可能会运行并且 //结果 1
和 //结果 3
可能无法运行。
有时它们可能全部运行,有时根本不会运行。
感谢您的帮助!
编辑:这是我的存储过程函数
async function stored_proc(opID, num, stat){
sql.executeTransaction( connection, {
procedure: "<stored procedure>",
params: {
OpID: {
val: opID,
type: sql.INT
},
num: {
val: num,
type: sql.STRING
},
Pass: {
val: stat,
type: sql.INT
},
ExtraData: {
val: "upload",
type: sql.STRING
}
}
} ).then( async function( data ) {
return data.transaction
.commit()
.then( async function() {
console.log("Updated database...." );
} );
}, function( err ) {
console.log( err );
} );
}
第二次编辑:我对此进行了更多研究,发现如果有多个结果要上传,它将永远上传第一组结果。我运行了一些 console.log()
,发现它总是会得到 find.Num
和 find.Status
。它只会记录第一个结果之后的每个结果的更新数据库
。我希望这是有道理的
最佳答案
在您的 stored_proc
中,您没有返回 Promise。
此外, promise 内的 promise 被认为是反模式,您可以轻松地将其链接起来。
async function stored_proc(opID, num, stat) {
return sql.executeTransaction(connection, {
procedure: "<stored procedure>",
params: {
OpID: {
val: opID,
type: sql.INT
},
num: {
val: num,
type: sql.STRING
},
Pass: {
val: stat,
type: sql.INT
},
ExtraData: {
val: "upload",
type: sql.STRING
}
}
})
.then(function (data) {
return data.transaction
.commit()
})
.then(function () {
console.log("Updated database....");
})
.catch((err) => {
console.log(err);
})
}
关于javascript - 如何在 JavaScript 中使顺序 if 语句异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836644/