Write promise-based flow in sequential steps
An async function always returns a promise. await pauses that function's continuation until the awaited value settles; it does not block the whole browser or make synchronous CPU work run on another thread.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function prepareLesson() {
await delay(50);
return { title: 'Promises', ready: true };
}
async function showLesson() {
try {
const lesson = await prepareLesson();
console.log(lesson.title); // Promises
} catch (error) {
console.error('Preparation failed:', error.message);
} finally {
console.log('Preparation attempt finished');
}
}
showLesson();Catch the awaited rejection
A rejected awaited promise throws at the await point, so try/catch can handle it. Calling an async function without awaiting or otherwise handling its promise can leave a rejection unhandled. If a catch cannot recover, add context and rethrow rather than returning an indistinguishable success value.
Sequential versus parallel
const [left, right] = await Promise.all([
loadLeft(),
loadRight()
]);This fragment belongs inside an async context and assumes both functions exist. Use it when requests are independent. If the second request needs the first request's result, sequential awaits express that dependency. Promise.all's rejection does not cancel the other request automatically.
Cleanup can change control flow
finally runs after try/catch, but a return or throw inside finally can override an earlier outcome. Keep it focused on cleanup. A pending-state button should be re-enabled there, while the success/error message belongs to the corresponding result path.
Practice
- Make prepareLesson throw and confirm the catch path.
- Compare two independent delays awaited sequentially versus Promise.all.
- Explain why
const x = prepareLesson()is a promise rather than the lesson object. - Use for...of with await for intentionally sequential work; do not assume forEach awaits async callbacks.
हिन्दी संकेत: await केवल async function का आगे का काम रोकता है, browser की पूरी execution नहीं।