Async/await helps you write code that waits for tasks to finish without blocking everything else. It makes working with things that take time, like loading data, easier to read and understand.
Async/await syntax in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
async function functionName() { const result = await someAsyncTask(); console.log(result); }
The async keyword before a function means it returns a promise and can use await.
The await keyword pauses the function until the promise resolves, then returns the value.
async function greet() { const message = await Promise.resolve('Hello!'); console.log(message); }
async function waitAndPrint() { await new Promise(resolve => setTimeout(resolve, 1000)); console.log('Waited 1 second'); }
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } }
This program fetches user data from a sample API and prints the user's name. It uses async/await to wait for the network response and handles errors if the fetch fails.
import fetch from 'node-fetch'; async function getUser() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const user = await response.json(); console.log(`User name: ${user.name}`); } catch (error) { console.error('Failed to get user:', error); } } getUser();
Always use try/catch blocks inside async functions to handle errors gracefully.
Remember that await only works inside functions marked with async.
Using async/await makes asynchronous code look like normal, easy-to-read code.
Async/await helps write clear code that waits for tasks without blocking.
Use async before functions and await before promises.
Handle errors with try/catch inside async functions.
Practice
await keyword do inside an async function in Node.js?Solution
Step 1: Understand the role of
Theawaitawaitkeyword pauses the execution of the async function until the promise it waits for settles (resolves or rejects).Step 2: Differentiate from blocking behavior
This pause only affects the async function, not the entire program, allowing other code to run concurrently.Final Answer:
It pauses the function execution until the promise resolves or rejects. -> Option DQuick Check:
await pauses async function = C [OK]
- Thinking await blocks the entire program
- Confusing await with callbacks
- Believing await speeds up code by skipping promises
Solution
Step 1: Recall async function declaration syntax
In Node.js, the correct way to declare an async function is by placing theasynckeyword before thefunctionkeyword.Step 2: Check each option
async function myFunc() {} matches the correct syntax:async function myFunc() {}. Others are invalid syntax.Final Answer:
async function myFunc() {} -> Option BQuick Check:
async before function keyword = B [OK]
- Placing async after function name
- Using colons or other symbols incorrectly
- Writing async inside parentheses
async function getNumber() {
return 42;
}
async function main() {
const result = await getNumber();
console.log(result);
}
main();Solution
Step 1: Understand async function return values
The functiongetNumberis async and returns 42, which means it returns a promise that resolves to 42.Step 2: Await the promise in
Themainawaitkeyword waits for the promise to resolve, soresultgets the value 42, which is then logged.Final Answer:
42 -> Option AQuick Check:
await unwraps promise value = D [OK]
- Expecting a Promise object printed
- Forgetting await causes Promise logged
- Using await outside async function
async function fetchData() {
const data = await fetch('https://api.example.com/data');
return data.json();
}
fetchData().then(console.log);Solution
Step 1: Analyze the fetchData function
The function awaits the fetch call, which returns a Response object. Callingdata.json()returns a promise.Step 2: Check promise handling for data.json()
Sincedata.json()returns a promise, it should be awaited to get the parsed JSON before returning.Final Answer:
Missing await before data.json() call -> Option AQuick Check:
Await promises before returning parsed data = A [OK]
- Not awaiting nested promises like data.json()
- Assuming fetch is unavailable in Node.js (modern Node supports it)
- Forgetting async keyword on async functions
async function getUserAndPosts() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
return { user, posts };
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}Solution
Step 1: Check async/await sequence
The code awaitsfetchUser()first, then uses the user ID to awaitfetchPosts(), ensuring sequential execution.Step 2: Verify error handling
The try/catch block correctly catches any errors from either await call and logs them, returning null on failure.Final Answer:
Correctly handles errors and fetches posts after user data -> Option CQuick Check:
Try/catch with sequential await = A [OK]
- Omitting try/catch for error handling
- Calling second await before first completes
- Returning promises without awaiting them
