Concurrent promises in JavaScript
Running many async operations at once.
const urls = ["/api/a", "/api/b", "/api/c"];
async function loadAll() {
const requests = urls.map((url) => fetch(url));
const responses = await Promise.all(requests);
return Promise.all(responses.map((r) => r.json()));
}
async function loadSafely() {
const results = await Promise.allSettled(urls.map((u) => fetch(u)));
return results.filter((r) => r.status === "fulfilled");
}
How it works
Promise.allwaits for every promise, failing fast.- Mapping over urls starts all requests immediately.
Promise.allSettledreports each outcome instead.
Keywords and builtins used here
Promiseasyncawaitconstfunctionreturn
The run, in numbers
- Lines
- 12
- Characters to type
- 379
- Tokens
- 113
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 71 seconds.
Step 4 of 5 in Promises, step 4 of 19 in Promises & async.