簡體   English   中英

使用 next() 的執行流程

[英]Execution flow using next()

我是新手,對 next() 函數的機制有疑問。

  1. 我是否正確,一旦 next() 被調用,它會立即觸發 app.get 的執行,而 next() 下的所有內容都將異步執行?
  2. 如果是這樣,為什么“我被處決了?” 一旦我在 setTimeout() 中設置了很大的延遲,就不會打印到控制台?

請在下面的代碼中解釋執行流程。

app.param('seriesId', (req, res, next) => {
  ... // Check for presence of series
  console.log('I am executed');
  next();
  setTimeout(() => {console.log('Am I executed?')}, 1000); // Prints for 100, does not print for 1000
});

app.get('/:seriesId', (req, res, next) => {
  ... // Call to db to get series object
  res.status(200).json({series: series});
});

調用next()將控制管道中的下一個中間件。 在您的示例中,這將是app.get

但是,該方法的行為不像return語句,因此您放置的任何代碼也將被執行。

給定下面的示例,如果您要啟動服務器並導航到http://localhost:1337/foo ,日志語句將是:

  1. 好吧,我們來了
  2. 執行獲取
const express = require('express');

const app = express();

app.param('param',(req, res, next) => {
    next();
    setTimeout(() => console.log('well here we are'), 1000);
});

app.get('/:param', (req, res) => {
    setTimeout(() => {
        console.log('executing the get');
        res.status(200).send();
    }, 2000);
});

app.listen(1337);
console.log('app started at http://localhost:1337');

在中間件中分支

避免混淆的一個好做法是確保在執行結束時調用next() 例如,不要這樣做:

if(aCondition) {
    next()
}
next(new Error('Condition was false'));

但是做:

if(aCondition) {
    next()
} else {
    next(new Error('Condition was false'));
}

或者,我所做的總是返回next()調用,以避免中間件執行任何進一步的代碼。

在中間件中執行異步代碼

最后一點:如果你需要在你的中間件中執行異步代碼,那么只有在這段代碼執行完后才調用next()

不要這樣做:

loadUserFromDB()
    .then(u => req.user = u);
next();

但是做:

loadUserFromDB()
    .then(u => {
         req.user = u;
         next();
    });

暫無
暫無

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

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