Read an Asynchronous Sequence
Read an Asynchronous Sequence
An async function returns a promise. await pauses that function's continuation while other work can proceed; it does not block the whole environment while waiting.
Before this topic, review Represent a Future Result if its terms are unfamiliar.
What you’ll learn
- Explain read an asynchronous sequence through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The continuation receives 80 after the immediate Requested line.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
async function report() {
const mark = await Promise.resolve(72);
console.log(mark);
}
report();
console.log("Requested");
Expected output
Requested
72Run in JavaScript compiler →Understanding Async/Await in JavaScript
In JavaScript, asynchronous programming allows you to perform long network requests or operations without blocking the main thread. async/await was introduced in ES2017 (ES8) and is built on top of Promises to make asynchronous code easier to read and write.
What is async ?
An async function is a function that always returns a Promise. Inside it, you can use the await keyword to pause execution until a Promise resolves.
What is await ?
The await keyword can only be used inside an async function. It waits for the Promise to resolve and returns the result. If the Promise is rejected, it throws the error.
Basic Example of Async/Await
Let’s simulate a network request using setTimeout wrapped in a Promise, then use async/await to call it.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
async function displayData() {
console.log("Fetching...");
const result = await fetchData();
console.log(result);
}
displayData();
Fetching... Data received!
Why use async/await over Promises?
While Promises work fine, they can lead to nested .then() chains, which are harder to read and maintain. async/await flattens this structure, making your code easier to follow.
Chaining Multiple Await Calls
You can chain multiple await calls sequentially just like synchronous code:
function delay(message, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(message), ms);
});
}
async function chainMessages() {
const msg1 = await delay("Step 1 complete", 1000);
console.log(msg1);
const msg2 = await delay("Step 2 complete", 1000);
console.log(msg2);
const msg3 = await delay("Step 3 complete", 1000);
console.log(msg3);
}
chainMessages();
Step 1 complete Step 2 complete Step 3 complete
What happens if a Promise fails?
If a Promise rejects, the await line throws an error. You must handle it using try...catch blocks inside async functions.
Using try/catch with Async/Await
function fetchUser() {
return new Promise((_, reject) => {
setTimeout(() => reject("User not found"), 1000);
});
}
async function getUserData() {
try {
const user = await fetchUser();
console.log(user);
} catch (error) {
console.error("Error:", error);
}
}
getUserData();
Error: User not found
Q: Can we use await outside of async function?
A: No, await can only be used inside an async function. Using it outside will result in a syntax error (except in top-level code in modern environments like recent versions of Node.js or browsers).
Summary
asyncfunctions return Promises.awaitpauses the execution of the function until the Promise resolves.- Use
try/catchto handle errors gracefully. - Async/await makes asynchronous code look and behave more like synchronous code.
Recognize the important boundary
await inside a loop can make independent operations sequential. Use promise combinations deliberately when work can overlap.
For independent subject results, compare Promise.all and other promise combinations before choosing a sequential await loop.
Try a small variation
JavaScript · original source for practice
async function report() {
const mark = await Promise.resolve(72);
console.log(mark);
}
report();
console.log("Requested");
Your task: Replace resolve(72) with resolve(80). Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The continuation receives 80 after the immediate Requested line.
JavaScript · complete worked variation
async function report() {
const mark = await Promise.resolve(80);
console.log(mark);
}
report();
console.log("Requested");
Expected output
Requested
80Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
async function report() {
const mark = await Promise.resolve(72);
console.log(mark);
}
report();
console.log("Requested");
Keep the useful idea
An async function returns a promise. await pauses that function's continuation while other work can proceed; it does not block the whole environment while waiting.
Check your variation against this explanation: The continuation receives 80 after the immediate Requested line.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.