简体   繁体   English

在 Node.js web 服务器中使用 Promise 处理请求

[英]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:使用 promise 处理请求是否有意义,如以下代码所示:

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?使用 Promise 是否会提高性能,尤其是在需要为每个请求处理长时间运行的进程时? Since Node.js is just a single thread, using a Promise might just be an illusion that it increases performance.由于 Node.js 只是一个单线程,因此使用 Promise 可能只是一种提高性能的错觉。

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.无论哪种方式,它都应该相当快,因为 Node 在内部使用 libuv 来实现非阻塞 IO,因此对于 Node 服务器来说,单线程通常不是问题。

Each promise has a cost in terms of memory and execution logic .每个 promise在 memory 和执行逻辑方面都有成本。 It is not free.它不是免费的。

So every useless promise adds overhead and possible bugs to your request flow.因此,每个无用的 promise 都会为您的请求流增加开销和可能的错误。

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() })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM