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

2023-05-05 12:17:20 +08:00
 cutemurphy2888

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

710 次点击
所在节点    Node.js
4 条回复
zbinlin
2023-05-05 18:26:44 +08:00
express 4 好像不支持 async function ,更新到 5 或者用 koa 吧
cutemurphy2888
2023-05-05 19:12:39 +08:00
@zbinlin 支持的 · 中间件 里面可以 await 一个异步结果·
zbinlin
2023-05-05 20:59:57 +08:00
@cutemurphy2888 可以用不代表支持呀,你这里就是打印不到 middleTwo await 之后的结果,就是因为 express 在调用 next() 时不是返回一个 promise ,导致你没办法 await 后一个 middleware 的 async 函数。

另外还有一个大问题就是这些 async 函数如果抛出异常的话,express 没办法捕获到
zbinlin
2023-05-05 22:26:30 +08:00
如果真的要用 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);
}
};

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/937507

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX