Understanding Promises in Node.js
Overview
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner alternative to callbacks for handling asynchronous code.
Creating a Promise
Here‘s how to create a basic Promise:
const myPromise = new Promise((resolve, reject) => {
const success = true; // Simulate success or failure
if (success) {
resolve('Operation was successful!');
} else {
reject('Operation failed.');
}
});
In this example, the Promise will either resolve or reject based on the simulated success condition.
Using Promises
To handle the result of a Promise, you can use the .then()
and .catch()
methods:
myPromise
.then(result => {
console.log(result); // Output: Operation was successful!
})
.catch(error => {
console.error(error); // Handle error
});
This approach allows you to handle successful outcomes and errors separately.
Chaining Promises
Promises can be chained to perform multiple asynchronous operations in sequence:
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched');
}, 1000);
});
}
fetchData()
.then(data => {
console.log(data); // Output: Data fetched
return 'Processed data';
})
.then(processedData => {
console.log(processedData); // Output: Processed data
})
.catch(error => {
console.error(error); // Handle any error
});
In this example, each .then()
receives the result of the previous Promise, allowing for smooth chaining.
Error Handling with Promises
It‘s important to handle errors in a chain of Promises. Any error that occurs in a Promise will skip to the nearest .catch()
:
function fetchDataWithError() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Error fetching data');
}, 1000);
});
}
fetchDataWithError()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error); // Output: Error fetching data
});