请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

下一个中间件是异步的时候,当前中间件 next 后的代码会先执行

老师讲到获取 postData 的数据是异步操作
我在每个 next() 方法的后面都添加了代码执行,原来我理解的结果是,所有的方法都调用结束。才会反向调用每个 next() 后面的代码。
理想结果应该是:1 => 2 => 3 => 4 => 5 => 6
但真实结果却是:1 => 2 => 6 => 3 => 4 => 5

请问老师,异步的中间件如果想得到 理想结果,该怎么写?

示例代码如下:

function getPostData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ username: "hzz", password: "123456" });
    }, 2000);
  });
}

// 请求开始整体拦截
app.use(function (req, res, next) {
  console.log("1 服务接受请求开始了...");
  next();
  console.log("6 next 之后 -- 服务请求结束了...");
});

// postdata 异步解析获取
app.use(async function (req, res, next) {
  console.log("2 post data 请求异步获取");
  req.body = await getPostData();
  console.log("\r\n3post data 请求结束");
  next();
  console.log("5 next 之后 -- post data");
});

// 接口入口
app.use("/api", function (req, res, next) {
  console.log("4 /api 开头的接头请求进入");
  next();
});

正在回答 回答被采纳积分+3

1回答

双越 2022-01-29 16:52:59

你把所有中间件函数都改成 async 函数,然后 next() 改完 await next() ,就可以了。

0 回复 有任何疑惑可以回复我~
  • 提问者 qq_木杉木_03622742 #1
    试了一下,还是1 => 2 => 6 => 3 => 4 => 5
    
    const express = require("express");
    
    const app = express();
    
    function getPostData() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ username: "hzz", password: "123456" });
        }, 2000);
      });
    }
    
    app.use((req, res, next) => {
      if (req.path !== "/favicon.ico") {
        next();
      }
    });
    
    // 请求开始整体拦截
    app.use(async function (req, res, next) {
      console.log("1 服务接受请求开始了...");
      await next();
      console.log("6 next 之后 -- 服务请求结束了...");
    });
    
    // postdata 异步解析获取
    app.use(async function (req, res, next) {
      console.log("2 post data 请求异步获取");
      req.body = await getPostData();
      console.log("\r\n3 post data 请求结束");
      await next();
      console.log("5 next 之后 -- post data");
    });
    
    // 接口入口
    app.use("/api", async function (req, res, next) {
      console.log("4 /api 开头的接头请求进入");
      await next();
    });
    
    app.listen(7788, () => {
      console.log("Server is running at port 7788");
    });
    回复 有任何疑惑可以回复我~ 2022-01-30 12:43:21
  • 双越 回复 提问者 qq_木杉木_03622742 #2
    你先吧  req.body = await getPostData(); 这一行改成  req.body = 'hello world' 试试。(测试执行顺序,先不要有其他的代码逻辑干扰)
    回复 有任何疑惑可以回复我~ 2022-01-30 20:25:53
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信