node.js - 如何在中间件中等待 next()

标签 node.js express

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

app.use((req, res, next) => {
  console.log(req);
  next();
});

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

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

最佳答案

我在我的项目中遇到了这个问题,我们快速解决了将中间件分成两部分的问题。您在路由之前添加第一部分,在之后添加的另一个部分中的“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}`);
});

这就是您遇到的问题。它会在这些行中打印一些东西。

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

-- 4

解决方法:

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}`);
});

您将中间件一分为二,以确保仅在执行完路由中的所有内容后才执行中间件 2。你会得到如下输出:

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

关于node.js - 如何在中间件中等待 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58069358/

相关文章:

如果对象中存在值,则使用 Javascript?

javascript - Node.js - Express.js JWT 总是在浏览器响应中返回一个无效的 token 错误

node.js - 应用程序在本地运行,在 Heroku - Node.JS 上崩溃

javascript - 如何从路由请求发送ws消息

node.js - 安装node.js后npm -v报错

javascript - Async.js 队列工作程序未完成

node.js - Express-Session、Connect-Redis 和 einaros/ws

node.js - 如何使用npm脚本重命名文件

javascript - 如何使用expressjs将数据从一个路由传递到另一个nodejs

node.js - NodeJS 管理后台认证策略