data.tables.map(async t => {
const table = await this.tablesService.tableCreate({
// 省略部分代码...
});
const contaxt1 = globalVarService.get('tableBulkInsert');
console.log('111', contaxt1)
return table;
});
const contaxt = globalVarService.get('tableBulkInsert');
console.log('222', contaxt)
如上代码,会先输出222的内容,后面才回输出111的内容。
循环内部的异步操作是按顺序执行的。
而在循环外部,没有使用await关键字等待异步操作的完成,所以在循环内部的异步操作还没有完成时,代码会继续执行后面的代码。
因此,先输出222后输出111的原因是循环内部的异步操作还没有完成时,代码继续执行了循环外部的代码。
要修正这个问题,可以将循环内部的异步操作封装成一个数组,然后使用Promise.all()方法等待所有异步操作完成后再执行后续代码。修改后的代码如下所示:
const promises = data.tables.map(async t => {
const table = await this.tablesService.tableCreate({
// 省略部分代码...
});
return table;
});
await Promise.all(promises);