浅谈Express异步进化史

2020-06-17 05:43:04易采站长站整理

return new Promise((resolve, reject) => {
setTimeout(() => {
res.locals = { title: 'Express Async Test' }; // 设置数据
res.render('index'); // 响应
}, 2000);
});
}

function doBizAsync(req, res, next) {
asyncFn(req)
.then(() => asyncFn2(req))
.then(() => asyncFn3(res))
.catch(next); // 统一异常处理
};

/* GET home page. */
router.get('/', doBizAsync);

module.exports = router;

3.3、async…await 处理Express异步逻辑

实际上,该方案也是需要 Promise 的支持,只是写法上,更直观,错误处理也更直接。

需要注意的是,Express是早期的方案,没有对async…await进行全局错误处理,所以可以采用包装方式,进行处理。


var express = require('express');
var router = express.Router();

function asyncFn(req) {
return new Promise((resolve, reject) => {
setTimeout(() => {
req.user = {}; // 设置当前请求的用户
resolve(req);
}, 2000);
});
}

function asyncFn2(req) {
return new Promise((resolve, reject) => {
setTimeout(() => {
req.auth = {}; // 设置用户权限
resolve();
}, 2000);
});
}

function asyncFn3(res) {
return new Promise((resolve, reject) => {
setTimeout(() => {

}, 2000);
});
}

async function doBizAsync(req, res, next) {
var result = await asyncFn(req);
var result2 = await asyncFn2(req);
res.locals = { title: 'Express Async Test' }; // 设置数据
res.render('index'); // 响应
};

const tools = {
asyncWrap(fn) {
return (req, res, next) => {
fn(req, res, next).catch(next); // async...await在Express中的错误处理
}
}
};

/* GET home page. */
router.get('/', tools.asyncWrap(doBizAsync)); // 需要用工具方法包裹一下

module.exports = router;

4、总结

虽然 koa 对更新、更好的用法(koa是generator,koa2原生async)支持的更好。但作为从 node 0.x 开始跟的我,对 Express 还是有特殊的好感。

以上的一些方案,已经与 koa 中使用无异,配合 Express 庞大的生态圈,无异于如虎添翼。

本文Github地址