[英]Using a Promise in a Node.js web server to handle requests
使用 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, () => {
});
使用 Promise 是否會提高性能,尤其是在需要為每個請求處理長時間運行的進程時? 由於 Node.js 只是一個單線程,因此使用 Promise 可能只是一種提高性能的錯覺。
性能應該與使用回調的任何等效代碼大致相同。 無論哪種方式,它都應該相當快,因為 Node 在內部使用 libuv 來實現非阻塞 IO,因此對於 Node 服務器來說,單線程通常不是問題。
每個 promise在 memory 和執行邏輯方面都有成本。 它不是免費的。
因此,每個無用的 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()
})
})
所以你可以重寫:
app.get('/', (req, res) => {
someLongRunningProcess()
.then(() => { res.end() })
.catch((error) => { res.status(500).end() })
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.