for await in JavaScript
Consuming an async iterable, one awaited value at a time.
async function* pages(total) {
for (let page = 1; page <= total; page += 1) {
await new Promise((resolve) => setTimeout(resolve, 1));
yield { page, rows: page * 2 };
}
}
async function main() {
let rows = 0;
for await (const page of pages(3)) {
rows += page.rows;
}
console.log("rows:", rows);
for await (const page of pages(5)) {
if (page.page === 2) break;
console.log("saw page", page.page);
}
const all = [];
for await (const value of [Promise.resolve(1), Promise.resolve(2)]) {
all.push(value);
}
console.log(all);
}
main();
How it works
- An async generator yields promises the loop awaits for you.
Symbol.asyncIteratoris the protocol behind it.- Breaking out calls the generator's return, so cleanup runs.
Keywords and builtins used here
Promiseasyncawaitbreakconstforfunctionifletofyield
The run, in numbers
- Lines
- 27
- Characters to type
- 533
- Tokens
- 175
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 100 seconds.
Step 1 of 2 in Iterating asynchronously, step 10 of 19 in Promises & async.