0
0
Node.jsframework~30 mins

Sequential vs parallel async execution in Node.js - Hands-On Comparison

Choose your learning style9 modes available
Sequential vs Parallel Async Execution in Node.js
📖 Scenario: You are building a simple Node.js script that fetches data from two different sources asynchronously. You want to learn how to run these fetches one after another (sequentially) and how to run them at the same time (in parallel) to see the difference in execution.
🎯 Goal: Build a Node.js script that first fetches two pieces of data sequentially using async/await, then modify it to fetch them in parallel using Promise.all. You will see how the total time changes depending on the approach.
📋 What You'll Learn
Create two async functions that simulate fetching data with a delay
Create a variable to hold the delay time in milliseconds
Write code to fetch data sequentially using async/await
Write code to fetch data in parallel using Promise.all
💡 Why This Matters
🌍 Real World
Many Node.js applications fetch data from multiple sources like APIs or databases. Knowing how to run these fetches sequentially or in parallel helps optimize performance and user experience.
💼 Career
Understanding async patterns like sequential and parallel execution is essential for backend and full-stack developers working with Node.js to write efficient and responsive applications.
Progress0 / 4 steps
1
Create async fetch functions
Create two async functions called fetchData1 and fetchData2. Each should return a Promise that resolves with the strings 'Data 1' and 'Data 2' respectively after a delay of 1000 milliseconds using setTimeout.
Node.js
Need a hint?

Use new Promise and setTimeout inside each async function to simulate delay.

2
Add delay variable
Create a constant variable called delay and set it to 1000 to represent the delay time in milliseconds.
Node.js
Need a hint?

Use const delay = 1000; to store the delay time.

3
Fetch data sequentially
Write an async function called fetchSequential. Inside it, use await to call fetchData1() and store the result in result1. Then await fetchData2() and store the result in result2. Return an array with result1 and result2.
Node.js
Need a hint?

Use await to wait for each fetch before starting the next.

4
Fetch data in parallel
Write an async function called fetchParallel. Inside it, use Promise.all with an array of fetchData1() and fetchData2() calls. Store the result in results and return it.
Node.js
Need a hint?

Use Promise.all to run both fetches at the same time and wait for both to finish.