如何在中间件中等待 next()

use*_*178 5 node.js express

使用express,我有一个像这样的中间件:

app.use((req, res, next) => {
  console.log(req);
  next();
});
Run Code Online (Sandbox Code Playgroud)

如何等待 next() 完成?我问的原因是我在 next() 之后添加了 console.log,此消息发生在下一个路由函数中的消息之前。

app.use(async(req, res, next) => {
  console.log(req);
  await next();
  console.log('should be the last print but ...');
});
Run Code Online (Sandbox Code Playgroud)

Ber*_*lip 5

我在项目中遇到了这个问题,我们快速解决了将中间件一分为二的问题。您可以在路由之前添加第一部分,并在之后添加的另一个部分中的“next()”之后添加要执行的内容。如果您需要访问相同的对象实例或某些内容,您可以随时将其保存在请求局部变量中。

我的例子:


const express = require('express');
const app = express();
const port = 5050;
const wait = (milliseconds) =>
    new Promise((res, rej) => {
        setTimeout(() => {
            res();
        }, milliseconds);
    });

const middleware = async (req, res, next) => {
    console.log('- 1');
    await wait(10);
    console.log('- 2');
    next();
    console.log('- 3');
    await wait(10);
    console.log('- 4');
    console.log('');
};
app.use(middleware);
app.get('/', async (req, res, next) => {
    console.log('-- 1');
    await wait(10);
    console.log('-- 2');
    console.log('hello');
    res.send('Hello World!');
    console.log('-- 3');
    await wait(10);
    console.log('-- 4');
    next();
    return;
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});
Run Code Online (Sandbox Code Playgroud)

这就会出现你遇到的问题。它会在这些行中打印一些东西。

- 1
- 2
-- 1
- 3
-- 2
hello
-- 3
- 4

-- 4
Run Code Online (Sandbox Code Playgroud)

解决方案:

const express = require('express');
const app = express();
const port = 5050;
const wait = (milliseconds) =>
    new Promise((res, rej) => {
        setTimeout(() => {
            res();
        }, milliseconds);
    });

const middleware1 = async (req, res, next) => {
    console.log('- 1');
    await wait(10);
    console.log('- 2');
    next();
};

const middleware2 = async (req, res, next) => {
    console.log('- 3');
    await wait(10);
    console.log('- 4');
    console.log('');
    next();
};

app.use(middleware1);
app.get('/', async (req, res, next) => {
    console.log('-- 1');
    await wait(10);
    console.log('-- 2');
    console.log('hello');
    res.send('Hello World!');
    console.log('-- 3');
    await wait(10);
    console.log('-- 4');
    next();
    return;
});
app.use(middleware2);

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});
Run Code Online (Sandbox Code Playgroud)

您将中间件分成两部分,以确保仅在执行路由中的所有内容后才执行中间件2。您将得到如下输出:

- 1
- 2
-- 1
-- 2
hello
-- 3
-- 4
- 3
- 4
Run Code Online (Sandbox Code Playgroud)

  • 我想你是对的!没有其他解决方案,Expressjs 的耻辱! (2认同)