【发布时间】:2021-09-25 18:03:05
【问题描述】:
我正在尝试使用异步调用,但是每当我输入 await 命令字时,脚本就无法运行。 任何建议都欣然接受。
底部的替代代码基于提供的注释
async function masterDeploy(PrimaryControl){
//2. Collect learning event dates from programme
LearnEvents = progLearnerEvent(progGuid)
.then(LearnEvents =>{
console.log(LearnEvents)
for (var b = 0; b < LearnEvents.length; b++) {
retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if await placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
return learnEventsArrComb
})
.then(learnEventsArrComb => {
console.log(learnEventsArrComb)
})
.catch(error =>
{DisplayError(error)}
);
另类从这里开始
LearnEvents = progLearnerEvent(progGuid)
await (LearnEvents =>{
//.then(LearnEvents =>{
console.log(LearnEvents)
for (var b = 0; b < LearnEvents.length; b++) {
await retLearnEvents(LearnEvents[b],progGuid,b) //need to wait for these results before moving to next loop, code does not run if placed at beginning of this line
console.log(FlightPlanArray)
learnEventsArrComb.push(FlightPlanArray)
console.log(learnEventsArrComb)
}
return learnEventsArrComb
})
//.then(learnEventsArrComb => {
// console.log(learnEventsArrComb)
//})
//.catch(error =>
// {DisplayError(error)}
//);
}
【问题讨论】:
-
首先将
.then()调用替换为await语法。 然后你可以在循环中添加await。 -
您的意思是将 progLearnerEvent 承诺也重写为异步吗?
-
progLearnerEvent(progGuid)已经返回了一个承诺,你不需要重写progLearnerEvent函数。你应该使用await而不是.then()的承诺。 -
你是这个意思吗?
-
并非如此。您需要
await承诺,并且根本不使用回调。
标签: javascript async-await promise