簡體   English   中英

使用快速路由處理程序和Promise-最佳做法是什么?

[英]using express route handlers and promises -what are the best practices?

我目前正在研究一個Web項目,並且試圖理解Node.js和表達。 我知道要實現異步且易於維護的代碼,我們應該使用Promise,但是我對以下情況感到困惑:我有一個REST API的路由處理程序,我應該返回Promise嗎? 即使在那里沒有完成異步工作? 即:

dummy_router.post("/", passport.authenticationMiddleware(), (req, res) => {
  return new Promise((fulfill, reject) => {
      var result = some_simple_functionality();
      if (result) {
          fulfill(result)
      } else {
          reject(err)
      }

  }).catch(function (error) {
      res.status(400).send('400: failed t :: ' + error + '\n');
  });
});

同樣是第二個問題。 如果我正在執行一些異步任務並承諾包含它們,那么這是一個好習慣嗎?

dummy_router.post("/", passport.authenticationMiddleware(), (req, res) => {
  some_promise().then((result) => {

  }, (err) => {

  }).catch(function (error) {
    res.status(400).send('400: failed t :: ' + error + '\n');
  });
});

將我的評論變成答案:

您的第一個示例是在不需要時實現承諾。 沒有理由將同步代碼包裝在Promise中。 這只會增加不必要的復雜性,也不會帶來任何好處。 Express對請求處理程序的返回值不做任何事情,因此根本沒有用它返回承諾。

您的第二個示例似乎正在使用返回諾言的實際異步操作。 這看起來通常是正確的,但尚不清楚為什么在.then()和.catch()上同時具有錯誤處理程序。 選擇一個或另一個,請注意,不重新拋出或返回被拒絕的承諾的拒絕處理程序會將承諾更改為已實現的承諾(覆蓋拒絕)。

因此,當您這樣做時:

  some_promise().then((result) => {

  }, (err) => {
      // unless you rethrow here, this will "handle" the error
      // and the promise will become fulfilled, not rejected
  }).catch(function (error) {
      res.status(400).send('400: failed t :: ' + error + '\n');
  });

(err) => {}處理程序會導致您的諾言拒絕被吃掉,除非您從中拋出或返回被拒絕的諾言。

因此,可能您想要的就是:

  some_promise().then((result) => {
      // code to process result here
      res.send(...);
  }).catch(function (error) {
      res.status(400).send('400: failed t :: ' + error + '\n');
  });

很少有過一個理由,同時使用.then()拒絕處理(第2參數.then()和隨后的.catch()處理程序。

有理由同時使用拒絕處理程序和catch()嗎?

不會。在幾種不常見的情況下,您可能兩者都想要,但在這種情況下(大多數情況下),只需要.catch()處理函數即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM