这里有一个计时器函数
const timer = (time) => {
return new Promise((resolve, reject) => {
console.log(`${time} timer start`);
setTimeout(() => {
console.log(`${time} timer end`);
resolve();
}, time);
});
};
我将用"for await of"one_answers"for 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()
第二,
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
可用于消费异步迭代。它也可以使用标准的可迭代项(就像您问题中的那个(,但使用标准的迭代项,它看起来与使用for..of
没有任何不同。
对于for await
可能有用的异步可迭代的示例:
const delay = ms => new Promise(res => setTimeout(res, ms));
async function* multiTimer() {
await delay(1000);
yield 1;
await delay(2000);
yield 2;
await delay(3000);
yield 3;
await delay(1000);
yield 4;
};
(async () => {
for await (const time of multiTimer()) {
console.log('got', time);
}
console.log('All the timers end');
})();
如果您有一个标准的可迭代,那么您应该使用for..of
,如果您有异步可迭代,则应该使用for await..of
。它们是为不同的情况而设计的。