express中使用asyncawait

    技术2022-07-11  99

    思路

    // 用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); } }, });
    Processed: 0.011, SQL: 9