下面是一个计时器函数
const timer = (time) => {
return new Promise((resolve, reject) => {
console.log(`${time} timer start`);
setTimeout(() => {
console.log(`${time} timer end`);
resolve();
}, time);
});
};
我将使用'for await of'和'for of'来调用此计时器函数。
首先,'for await of'
async function runForAwaitOf() {
const times = [300, 100, 700, 500];
for await (let time of times) {
await timer(time);
}
console.log('All the timers end');
}
runForAwaitOf()
第二,'for of'
async function runForOf() {
const times = [300, 100, 700, 500];
for (let time of times) {
await timer(time);
}
console.log('All the timers end');
}
runForOf()
当我运行上述代码时,我没有看到它们之间的任何差异。
如果它们的结果是相同的,为什么ECMA会使用"for await of"呢?
for...await of
是关于处理异步迭代器,而不仅仅是处理 Promise 可迭代对象。 - VLAZ