0
0
NodejsHow-ToBeginner · 3 min read

How to Use Promises in Node.js for Asynchronous Code

In Node.js, 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.

javascript
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.

javascript
const delayedSuccess = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Operation completed successfully!');
  }, 1000);
});

delayedSuccess
  .then(message => console.log(message))
  .catch(error => console.error(error));
Output
Operation completed successfully!
⚠️

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.

javascript
/* 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
Output
undefined 10
📊

Quick Reference

MethodDescription
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

Use new Promise to create asynchronous operations that can succeed or fail.
Chain .then() to handle success and .catch() to handle errors.
Always return promises inside .then() to maintain chaining.
Avoid mixing callbacks and promises to keep code clear and manageable.
Use .finally() to run cleanup code after promise completion.