V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cutemurphy2888
V2EX  ›  Node.js

middleOne 如何打印到 middleTwo await 之后的结果·· "express": "^4.18.2",

  •  
  •   cutemurphy2888 · 358 天前 · 686 次点击
    这是一个创建于 358 天前的主题,其中的信息可能已经有所发展或是发生改变。

    const express = require('express'); const app = express();

    const vv = { }

    const middleOne = async (req, res, next) => { await next(); console.log(vv, 'middle1'); }

    const haha = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('hahahhahhah'); }, 3000); }) }

    const middleTwo = async (req, res, next) => { const result = await haha(); vv.uname = result; console.log(vv, 3232); next(); }

    app.use(middleOne); app.use(middleTwo);

    app.get('/', (req, res, next) => { res.send({ 'cute': 'murphy' }); })

    app.listen(3002, (res) => { console.log(res, 22); })

    4 条回复    2023-05-05 22:26:30 +08:00
    zbinlin
        1
    zbinlin  
       358 天前
    express 4 好像不支持 async function ,更新到 5 或者用 koa 吧
    cutemurphy2888
        2
    cutemurphy2888  
    OP
       357 天前
    @zbinlin 支持的 · 中间件 里面可以 await 一个异步结果·
    zbinlin
        3
    zbinlin  
       357 天前
    @cutemurphy2888 可以用不代表支持呀,你这里就是打印不到 middleTwo await 之后的结果,就是因为 express 在调用 next() 时不是返回一个 promise ,导致你没办法 await 后一个 middleware 的 async 函数。

    另外还有一个大问题就是这些 async 函数如果抛出异常的话,express 没办法捕获到
    zbinlin
        4
    zbinlin  
       357 天前
    如果真的要用 async function ,可以这样用:

    let resolve;
    const promise = new Promise(r => {
    resolve = r;
    });

    const middleOne = async (req, res, next) => {
    next();
    const vv = await promise;
    console.log(vv, "middle1");
    };

    const haha = () => {
    return new Promise((resolve, _reject) => {
    setTimeout(() => {
    resolve("hahahahah");
    });
    });
    };

    const middleTwo = async (req, res, next) => {
    try {
    const result = await haha();
    resolve({
    name: result,
    });
    next();
    } catch (ex) {
    next(ex);
    }
    };
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2708 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 10:54 · PVG 18:54 · LAX 03:54 · JFK 06:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.