Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const app = express();
- app.use(async(req, res, next) => {
- await authenticate(req);
- next();
- });
- app.get('/route', async(req, res) => {
- const result = await request('http://example.com');
- res.end(result);
- });
- app.use((err, req, res, next) => {
- console.error(err);
- res
- .status(500)
- .end('error');
- })
- app.listen(8080);
- app.get('/route', (req, res, next) => {
- throw new Error('Error');
- res.end(result);
- });
- Layer.prototype.handle_request = function handle(req, res, next) {
- var fn = this.handle;
- if (fn.length > 3) {
- // not a standard request handler
- return next();
- }
- try {
- fn(req, res, next);
- } catch (err) {
- next(err);
- }
- };
- app.get('/route', async(req, res, next) => {
- try {
- const result = await request('http://example.com');
- res.end(result);
- } catch(err) {
- next(err);
- }
- });
- const asyncHandler = fn => (req, res, next) => {
- return Promise
- .resolve(fn(req, res, next))
- .catch(next);
- };
- module.exports = asyncHandler;
- app.use(asyncHandler(async(req, res, next) => {
- await authenticate(req);
- next();
- }));
- app.get('/async', asyncHandler(async(req, res, next) => {
- const result = await request('http://example.com');
- res.end(result);
- }));
- // Any rejection will go to the error handler
Add Comment
Please, Sign In to add comment