为什么我的循环继续没有等待async/await完成?



所以在高层次上,我希望这是如何工作的。

  1. Function1将被用户踢开。
  2. 执行过程中Function2会在Function1内部被踢开。
  3. Function2将在数组的每次循环中被启动。
  4. 在进入下一个循环之前,我需要等待每个Function2完成。

当前正在运行Function2的正确次数,但没有等待每个previous完成。

async function1() {
let index = 0
for (const row of this.submissions) {
if (row.EXCEL_CHECK === 1) {
(async() => {
let indexAdd = await this.function2(index)
})();
}
index = index + indexAdd
}
}
async function2(inlineIndex) {

// Create someArray
try {
await this.getSomeArray(something);
} catch (e) {
console.log('Try/Catch Error: ' + e);
}
let x = this.someArray.length - 1;
return x;

}

注意,我只添加异步箭头,因为我得到这个结果时,我试图只是把

let indexAdd = await function2(index)

错误:

'await' expressions are only allowed within async functions and at the top levels of modules.ts

注意,为了便于解释,我已经简化了函数,但是这个调用是在函数本身的深处进行的。

Function1已经是一个异步函数,所以你不需要用匿名异步箭头函数包装Function2调用。

所以你可以安全地删除这些:

// - (async() => {
let indexAdd = await this.function2(index)
// - })();
await (async() => {
let indexAdd = await this.function2(index)
})();

只需再添加一个匿名await函数。

或者完全删除async,因为函数1已经是async

//(async() => {
let indexAdd = await this.function2(index)
//})();

和确保func1被调用await

await function1();

最新更新