0
0
Node.jsframework~30 mins

Promise.race and Promise.allSettled in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Promise.race and Promise.allSettled in Node.js
📖 Scenario: You are building a Node.js app that fetches data from multiple sources. Sometimes, you want to get the fastest response, and other times you want to know the result of all requests, whether they succeed or fail.
🎯 Goal: Learn how to use Promise.race to get the first completed promise and Promise.allSettled to get the results of all promises regardless of success or failure.
📋 What You'll Learn
Create three promises simulating data fetches with different delays
Create a variable to hold a timeout threshold in milliseconds
Use Promise.race to get the first promise that settles
Use Promise.allSettled to get the results of all promises
💡 Why This Matters
🌍 Real World
Fetching data from multiple APIs where you want either the fastest response or a full report of all responses including errors.
💼 Career
Understanding Promise.race and Promise.allSettled is essential for Node.js developers to handle multiple asynchronous operations efficiently and robustly.
Progress0 / 4 steps
1
Create three promises simulating data fetches
Create three promises named fetchUser, fetchPosts, and fetchComments. Each promise should resolve with a string: 'User data', 'Posts data', and 'Comments data' respectively. Use setTimeout to simulate delays of 3000ms, 2000ms, and 1000ms respectively.
Node.js
Need a hint?

Use new Promise and setTimeout to simulate delayed responses.

2
Create a timeout threshold variable
Create a constant variable named timeout and set it to 2500 milliseconds. This will be used to compare delays.
Node.js
Need a hint?

Use const timeout = 2500; to set the threshold.

3
Use Promise.race to get the first completed promise
Use Promise.race with an array containing fetchUser, fetchPosts, and fetchComments. Assign the result to a constant named fastestResponse.
Node.js
Need a hint?

Use Promise.race with the three promises inside an array.

4
Use Promise.allSettled to get all results regardless of outcome
Use Promise.allSettled with an array containing fetchUser, fetchPosts, and fetchComments. Assign the result to a constant named allResults.
Node.js
Need a hint?

Use Promise.allSettled with the three promises inside an array.