express中使用async/await

思路

// 用async/await写express时候的包装函数1
const wrap = fn => (...args) => fn(...args).catch(args[2])

// 用async/await写express时候的包装函数2
//const wrap1 = function (fn) {
//    return (req, res, next) => {
//        fn(req, res, next).catch(next)
//    }
//}

// 使用方法,warp函数为上面定义的方法
// app.get('/', wrap(async (req, res, next) => {
//     const company = await getCompanyById(req.query.id)
//     const stream = getLogoStreamById(company.id)
//     stream.on('error', next).pipe(res)
// }))
// express异步改造
//入口文件
const Layer = require('express/lib/router/layer')
Object.defineProperty(Layer.prototype, 'handle', {
    enumerable: true,
    get() {
        return this.__handle;
    },
    set(fn) {
        if (fn.length === 4) {
            this.__handle = fn;
        } else {
            this.__handle = (req, res, next) =>
                Promise.resolve(fn(req, res, next)).catch(next);
        }
    },
});

你可能感兴趣的:(Express笔记)