Level: Intermediate | Player: 15_Promise
Learning Objectives
- We know that the
asyncfunction always returns Promise. - With
await, the Promise value can be received synchronously. - Handle asynchronous errors with
try/catch. - Know the difference between parallel execution and sequential execution.
- Processes efficiently by combining
Promise.allandawait.
1. async function
For functions with the async keyword, the return value is automatically wrapped in a Promise.
async function f() {
return 42;
}
f().then((v) => console.log(v)); // 42
2. await
await pauses function execution until the Promise is determined. async Can only be used inside functions (excluding top-level modules).
async function main() {
const value = await Promise.resolve(10);
console.log(value); // 10
}
3. try / catch
Asynchronous errors are caught with try/catch.
async function load() {
try {
const data = await fetchData();
console.log(data);
} catch (err) {
console.error(err);
}
}
4. Parallel vs sequential
Successive await operations are slow because the next operation begins only after the previous operation has finished. Parallelize independent tasks with Promise.all.
//Slow (sequential)
const a = await fetchA();
const b = await fetchB();
//Fast (parallel)
const [a, b] = await Promise.all([fetchA(), fetchB()]);
Core example
| file | Contents covered |
|---|---|
| 01_async_basic.js | async functions and await basics |
| 02_try_catch.js | Error handling with try/catch |
| 03_promise_all.js | await + Promise.all |
| 04_parallel.js | Parallel vs sequential time comparison |
⚠️ Common Mistakes
- Using
awaitin a function other thanasync→ SyntaxError. - Waste time by writing independent tasks as consecutive
await. - Unhandled rejection by awaiting without
try/catch. forEach((x) => await ...)does not work (callback is not async).- Use the return value of the async function as is without resolving it with then.
❓ Frequently Asked Questions (FAQ)
Q1. Can await be used at the top level of a module? A. It is possible in top-level await (ESM only) in ES2022.
Q2. What if an async function throws? A. The returned Promise is in a rejected state.
Q3. Which is better: await or .then? A. Readability is usually better with await. branch/combination When simple, .then is sufficient.