Skip to content

Instantly share code, notes, and snippets.

@tnewman
Last active December 15, 2018 01:01
Show Gist options
  • Save tnewman/7fe3d7a4447ca28894443858db41cc92 to your computer and use it in GitHub Desktop.
Save tnewman/7fe3d7a4447ca28894443858db41cc92 to your computer and use it in GitHub Desktop.
Async Callbacks with Express
"use strict";
const express = require('express');
const app = express();
const port = 3000;
function asyncHandler(fn) {
return function(req, res, next) {
Promise
.resolve(fn(req, res, next))
.catch(next);
}
}
function asyncErrorHandler(fn) {
return function(err, req, res, next) {
Promise
.resolve(fn(err, req, res, next))
.catch(next);
}
}
app.get('/test', asyncHandler(async (req, res) => {
await new Promise(resolve => {
resolve();
});
res.send({
message: 'G!'
});
}));
app.get('/error', asyncHandler(async (req, res) => {
await new Promise((resolve, reject) => {
reject(new Error('NG!'));
});
}));
app.use(asyncErrorHandler(async function(err, req, res, next) {
res.send({
error: err.message
});
}));
app.listen(port, () => console.log('Ready for Work!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment