在JavaScript中,可以使用for...of
循环结合await
关键字来按顺序执行带有可选异步调用的循环。下面是一个示例代码:
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const asyncFunc = async (item) => {
// 模拟异步调用
await delay(1000);
console.log(item);
};
const items = [1, 2, 3, 4, 5];
const executeLoop = async () => {
for (const item of items) {
// 可选的异步调用
if (item % 2 === 0) {
await asyncFunc(item);
}
else {
console.log(item);
}
}
};
executeLoop();
在上面的示例中,items
数组包含了要遍历的元素。在executeLoop
函数中,我们使用for...of
循环来遍历数组中的每个元素。在每次循环中,我们检查元素是否满足某个条件(例如,偶数),如果满足条件,则调用asyncFunc
函数进行异步操作,否则直接打印该元素。
在asyncFunc
函数中,我们使用await
关键字来等待一个模拟的异步操作完成。在这里,我们使用了delay
函数来模拟异步操作,它会延迟1秒钟后返回一个Promise
。
通过上述代码,我们可以保证异步调用在循环内按顺序执行,并且保持了循环的顺序。