Promises in JavaScript are a way to handle asynchronous operations in a more organized and readable manner. They are a way to handle the errors and results of an asynchronous operation in a single place. The Promise.reject()
function is a way to create a promise that is already rejected, which can be useful in certain situations.
Step 1: Import the promise
module
const Promise = require('promise');
Step 2: Create a rejected promise using Promise.reject()
const rejectedPromise = Promise.reject("Error message");
Step 3: Attach a rejection handler using .catch()
rejectedPromise.catch((error) => {
console.log(error);
});
Practical Examples
Example 1: Validation in Async Functions
async function validateUser(userId) {
if (!userId) {
return Promise.reject(new Error('User ID is required'));
}
// Continue with user validation
const user = await fetchUser(userId);
return user;
}
validateUser(null)
.then(user => console.log('User:', user))
.catch(error => console.error('Validation failed:', error.message));
Example 2: Early Exit in Promise Chains
function processOrder(orderId) {
return checkInventory(orderId)
.then(available => {
if (!available) {
return Promise.reject(new Error('Item out of stock'));
}
return processPayment(orderId);
})
.then(paymentResult => {
return shipOrder(orderId);
})
.catch(error => {
console.error('Order processing failed:', error.message);
// Handle error appropriately
});
}
Example 3: Mock Testing
// Mock function for testing error scenarios
function mockFailedAPICall() {
return Promise.reject(new Error('API connection failed'));
}
// Test error handling
mockFailedAPICall()
.then(data => {
console.log('This should not execute');
})
.catch(error => {
console.error('Expected error:', error.message);
});
Example 4: Conditional Promise Creation
function fetchData(shouldFail = false) {
if (shouldFail) {
return Promise.reject(new Error('Simulated failure'));
}
return fetch('/api/data')
.then(response => response.json());
}
// Usage
fetchData(true)
.catch(error => console.log('Handled error:', error.message));
Best Practices
- Always provide meaningful error messages when using
Promise.reject()
- Use Error objects instead of strings for better stack traces
- Handle rejected promises with
.catch()
or try/catch in async functions - Chain error handlers appropriately in promise chains
Conclusion
Promise.reject()
is a powerful tool for error handling in asynchronous JavaScript code. It allows you to create rejected promises explicitly, enabling better control flow and error management in your Node.js applications.