这是一个定时器函数
const timer = (time) => {
return new Promise((resolve, reject) => {
console.log(`${time} timer start`);
setTimeout(() => {
console.log(`${time} timer end`);
resolve();
}, time);
});
};
Run Code Online (Sandbox Code Playgroud)
我将用“for wait of”和“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()
Run Code Online (Sandbox Code Playgroud)
二、“为之”
async function runForOf() {
const times = [300, 100, 700, 500];
for (let time of times) {
await timer(time);
}
console.log('All the timers end');
}
runForOf()
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我没有看到它们之间有任何差异。
如果结果相同,为什么 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');
})();Run Code Online (Sandbox Code Playgroud)
如果你有一个标准的可迭代,你应该使用for..of,如果你有一个异步可迭代,你应该使用for await..of。它们是针对不同情况而设计的。