Explore the promise.race() method in Node.js with easy-to-follow steps for practical application. Dive in to grasp its usage effortlessly!
What is Promise.race()?
Promise.race() is a method that takes an array of promises and returns a single promise that resolves or rejects as soon as one of the promises in the array resolves or rejects.
Basic Syntax
Promise.race(iterable);
Example 1: Basic Promise.race
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'two');
});
Promise.race([promise1, promise2]).then((value) => {
console.log(value); // "two" - promise2 was faster
});
Example 2: Timeout Pattern
const fetchWithTimeout = (url, timeout = 5000) => {
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Request timeout')), timeout);
});
const fetchPromise = fetch(url);
return Promise.race([fetchPromise, timeoutPromise]);
};
fetchWithTimeout('https://api.example.com/data', 3000)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error.message));
Example 3: Multiple API Endpoints
const endpoints = [
'https://api1.example.com/data',
'https://api2.example.com/data',
'https://api3.example.com/data'
];
const fetchPromises = endpoints.map(url => fetch(url));
Promise.race(fetchPromises)
.then(response => response.json())
.then(data => {
console.log('First response received:', data);
})
.catch(error => {
console.error('All requests failed:', error);
});
Example 4: Resource Loading
const loadImage = (src) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
};
const images = [
'https://cdn1.example.com/image.jpg',
'https://cdn2.example.com/image.jpg',
'https://cdn3.example.com/image.jpg'
];
Promise.race(images.map(loadImage))
.then(img => {
console.log('First image loaded:', img.src);
document.body.appendChild(img);
})
.catch(error => {
console.error('Failed to load any image:', error);
});
Example 5: Database Connection
const connectToDatabase = async () => {
const primaryDB = connectToPrimary();
const secondaryDB = connectToSecondary();
const backupDB = connectToBackup();
try {
const connection = await Promise.race([
primaryDB,
secondaryDB,
backupDB
]);
console.log('Connected to database:', connection.name);
return connection;
} catch (error) {
console.error('Failed to connect to any database:', error);
throw error;
}
};
Best Practices
- Error Handling: Always include error handling when using Promise.race()
- Timeout Implementation: Use Promise.race() to implement timeouts for long-running operations
- Performance Optimization: Use it to get the fastest response from multiple sources
- Fallback Mechanisms: Implement fallback strategies when the first promise fails
Conclusion
Promise.race() is a powerful tool for handling competitive asynchronous operations where you only care about the first result. It’s particularly useful for implementing timeouts, getting the fastest response from multiple sources, and creating responsive applications.