Johann
Johann

Reputation: 29867

Using a Promise in a Node.js web server to handle requests

Does it make sense to use a promise to handle a request as shown in the following code:

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

app.get('/', (req, res) => {
    return new Promise(async function (resolve) {
                       await someLongRunningProcess();
                       resolve();
     })
     .then() {
        res.end();
     };
});

// Start the server
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {

});

Would there be any performance improvement of using a Promise, especially if a long running process needs to be handled for each request? Since Node.js is just a single thread, using a Promise might just be an illusion that it increases performance.

Upvotes: 0

Views: 1072

Answers (2)

Manuel Spigolon
Manuel Spigolon

Reputation: 12870

Each promise has a cost in terms of memory and execution logic. It is not free.

So every useless promise adds overhead and possible bugs to your request flow.

app.get('/', (req, res) => {
  /**
   * Promise doesn't not support this signature.
   * You must use function (resolve, reject){}.
   *
   * If you have an error in this function, you will
   * get an UnhandledPromiseRejectionWarning
   */
  return new Promise(async function (resolve) {
    /**
     * if you are awaiting `someLongRunningProcess`,
     * you have already a promise so creating a new
     * one add overhead.
     */
    await someLongRunningProcess()
    resolve()
  })
    .then(() => {
      res.end()
    })
    .catch((error) => {
      /**
       * to avoid UnhandledPromiseRejectionWarning and memory leak,
       * be sure to add always a .catch in your promise chain
      */
      res.status(500).end()
    })
})

So you can rewrite:

app.get('/', (req, res) => {
  someLongRunningProcess()
    .then(() => { res.end() })
    .catch((error) => { res.status(500).end() })
})

Upvotes: 1

Nicky McCurdy
Nicky McCurdy

Reputation: 19524

Performance should be about the same as any equivalent code using callbacks. Either way it should be fairly fast, as Node internally uses libuv for nonblocking IO, so having a single thread isn't usually an issue for Node servers.

Upvotes: 0

Related Questions