MENU
Asynchronous Iteration
Usable only inside an async function, the for await...offor await...of for await...of statement loops over sync and async iterables such as String, Array, Array-like objects (eg. arguments / NodeList), TypedArray, Map, Set and user-defined async/sync iterables.One important use case of asynchronous iteration is pagination, ie. downloading more resources (for the next page) through AJAX calls upon user's navigation.
Over iterables Over iterables Over iterables
RESETRUNFULL
<!DOCTYPE html><html><body><script>
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve(
{ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
}
};
}};(async function() {
for await (let num of asyncIterable) {
console.log(num);
}})();// 0// 1// 2
</script></body><html>
Over generators Over generators Over generators
RESETRUNFULL
<!DOCTYPE html><html><body><script>
async function* asyncGenerator() {
let i = 0;
while (i < 3) {
yield i++;
}}(async function() {
for await (let num of asyncGenerator()) {
console.log(num);
}})();// 0// 1// 2
</script></body><html>
Be aware of yielding rejected promises from sync generator. In such case for await...of throws when consuming rejected promise and DOESN'T CALL finally blocks within that generator. This can be undesireable if you need to free some allocated resources with try/finally.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* generatorWithRejectedPromises() {
try {
yield 0;
yield 1;
yield Promise.resolve(2);
yield Promise.reject(3);
yield 4;
throw 5;
} finally {
console.log('called finally')
}}(async function() {
try {for await (let num of
generatorWithRejectedPromises()){
console.log(num);
}
} catch (e) {
console.log('catched', e)
}})();// 0// 1// 2// catched 3// compare with for-of loop:try {
for (let numOrPromise of
generatorWithRejectedPromises()){
console.log(numOrPromise);
}} catch (e) {
console.log('catched', e)}// 0// 1// Promise { 2 }// Promise { <rejected> 3 }// 4// catched 5// called finally(async function() {
try {for (let numOrPromise of
generatorWithRejectedPromises()) {
console.log(await numOrPromise);
}
} catch (e) {
console.log('catched', e)
}})()// 0// 1// 2// catched 3// called finally
</script></body><html>
(reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Statements/for-await...of )