我在这样的循环中有一系列的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
可能运行一次,而//result 1
和//result 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
。对于第一个结果之后的每个结果,它只会记录Updated database
。我希望这是有道理的
答案 0 :(得分:2)
在您的stored_proc
中,您没有返回承诺。
另外,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);
})
}