[nodejs]

Table of Contents


How to Use Promises in Node.js

In Node.js, promises provide a way to handle asynchronous operations more effectively. They allow you to write asynchronous code in a more synchronous-like manner, making it easier to manage complex control flows.

What are Promises?

Promises in Node.js are objects that represent the eventual completion or failure of an asynchronous operation. They can be in one of three states: pending, fulfilled, or rejected. Promises are especially useful when working with functions that return Promises, such as database queries or HTTP requests.

Example Usage

const myPromise = new Promise((resolve, reject) => {
  // some asynchronous operation
  if (operationSuccessful) {
    resolve(result);
  } else {
    reject(error);
  }
});

myPromise.then((result) => {
  // handle successful result
}).catch((error) => {
  // handle error
});

In this example, myPromise represents an asynchronous operation. If the operation is successful, it resolves with a result; otherwise, it rejects with an error.

Creating a RESTful API with Express in Node.js

Express is a popular web application framework for Node.js. It provides a robust set of features to develop web and mobile applications. One of the most common use cases for Express is building RESTful APIs.

Creating Routes

const express = require('express');
const app = express();

app.get('/api/users', (req, res) => {
  // handle GET request for retrieving users
});

app.post('/api/users', (req, res) => {
  // handle POST request for creating a new user
});

// additional routes for updating and deleting users

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example, we define routes to handle GET and POST requests for managing users. Express makes it easy to define routes for different HTTP methods and URIs, allowing you to create a RESTful API with minimal effort.


By following these guidelines, you can effectively use promises in Node.js and create RESTful APIs using Express. These approaches can help you build more efficient and manageable applications.

References: