以下是两种常见的解决方案:
1.使用async/await关键字:
async function asyncMethod(item) {
}
async function loop() {
const array = [1, 2, 3, 4, 5];
for (const item of array) {
await asyncMethod(item);
}
}
loop();
2.使用Promise和then方法:
function asyncMethod(item) {
return new Promise((resolve, reject) => {
resolve();
});
}
function loop() {
const array = [1, 2, 3, 4, 5];
let promise = Promise.resolve();
array.forEach(item => {
promise = promise.then(() => asyncMethod(item));
});
}
loop();
对应业务: 类似城市级联器的懒加载回显,根据后端返回数组的长度进行循环,需要逐级调用不同的接口,需等上一级调用完成,生成对应的树结构时。