0
0
Node.jsframework~30 mins

Promise.all for parallel execution in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Promise.all for Parallel Execution in Node.js
📖 Scenario: You are building a Node.js script that fetches data from multiple URLs. To make the process faster, you want to run all fetches at the same time instead of waiting for each one to finish before starting the next.
🎯 Goal: Build a Node.js script that uses Promise.all to fetch data from multiple URLs in parallel and handle the results together.
📋 What You'll Learn
Create an array called urls with three exact URL strings.
Create a function called fetchData that returns a promise resolving with a string.
Use Promise.all with urls.map(fetchData) to run all fetches in parallel.
Add a final .then block to handle the array of results.
💡 Why This Matters
🌍 Real World
Fetching multiple data sources at the same time speeds up web applications and scripts, improving user experience and efficiency.
💼 Career
Understanding Promise.all is essential for Node.js developers to handle multiple asynchronous operations efficiently in real projects.
Progress0 / 4 steps
1
Create the URLs array
Create an array called urls with these exact strings: 'https://api.example.com/data1', 'https://api.example.com/data2', and 'https://api.example.com/data3'.
Node.js
Need a hint?

Use square brackets [] to create an array and separate the URLs with commas.

2
Create the fetchData function
Create a function called fetchData that takes a parameter url and returns a promise that resolves with the string `Data from ${url}` after 100 milliseconds using setTimeout.
Node.js
Need a hint?

Use new Promise and setTimeout to simulate an async fetch that resolves after 100 milliseconds.

3
Use Promise.all to fetch all URLs in parallel
Create a variable called allData and assign it the result of Promise.all called with urls.map(fetchData) to run all fetches in parallel.
Node.js
Need a hint?

Use urls.map(fetchData) inside Promise.all to run all fetches at the same time.

4
Add a then block to handle all results
Add a .then block to allData that takes a parameter results and inside the block, create a variable firstResult assigned to results[0].
Node.js
Need a hint?

Use allData.then(results => { ... }) and inside the block assign const firstResult = results[0].