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); })
1
zbinlin 2023-05-05 18:26:44 +08:00
express 4 好像不支持 async function ,更新到 5 或者用 koa 吧
|
2
cutemurphy2888 OP @zbinlin 支持的 · 中间件 里面可以 await 一个异步结果·
|
3
zbinlin 2023-05-05 20:59:57 +08:00
@cutemurphy2888 可以用不代表支持呀,你这里就是打印不到 middleTwo await 之后的结果,就是因为 express 在调用 next() 时不是返回一个 promise ,导致你没办法 await 后一个 middleware 的 async 函数。
另外还有一个大问题就是这些 async 函数如果抛出异常的话,express 没办法捕获到 |
4
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); } }; |