How to Use Promises in Node.js for Asynchronous Code
Promises are used to handle asynchronous operations by representing a value that may be available now, later, or never. You create a Promise with a function that resolves or rejects, then use .then() and .catch() to handle success or errors.Syntax
A Promise is created using the new Promise() constructor which takes a function with two parameters: resolve and reject. Inside this function, you perform your asynchronous task and call resolve(value) if it succeeds or reject(error) if it fails. You handle the result by chaining .then() for success and .catch() for errors.
const myPromise = new Promise((resolve, reject) => { // asynchronous task if (/* success condition */) { resolve('Success!'); } else { reject('Failure!'); } }); myPromise .then(result => console.log(result)) .catch(error => console.error(error));
Example
This example shows a promise that simulates a delay using setTimeout. It resolves after 1 second with a success message. The .then() method logs the success, and .catch() would catch any errors.
const delayedSuccess = new Promise((resolve, reject) => { setTimeout(() => { resolve('Operation completed successfully!'); }, 1000); }); delayedSuccess .then(message => console.log(message)) .catch(error => console.error(error));
Common Pitfalls
One common mistake is forgetting to return a promise inside .then(), which breaks chaining. Another is not handling errors with .catch(), causing unhandled promise rejections. Also, mixing callbacks and promises can lead to confusing code.
/* Wrong: Missing return breaks chaining */ function getNumber() { return new Promise(resolve => resolve(5)); } getNumber() .then(num => { new Promise(resolve => resolve(num * 2)); // Not returned }) .then(result => console.log(result)); // result is undefined /* Right: Return the promise to chain */ getNumber() .then(num => { return new Promise(resolve => resolve(num * 2)); }) .then(result => console.log(result)); // Logs 10
Quick Reference
| Method | Description |
|---|---|
| new Promise((resolve, reject) => {...}) | Create a new promise with resolve and reject functions |
| .then(successHandler) | Handle the resolved value of the promise |
| .catch(errorHandler) | Handle any error or rejection |
| .finally(handler) | Run code after promise settles, regardless of outcome |
Key Takeaways
new Promise to create asynchronous operations that can succeed or fail..then() to handle success and .catch() to handle errors..then() to maintain chaining..finally() to run cleanup code after promise completion.