Last active
December 15, 2018 01:01
-
-
Save tnewman/7fe3d7a4447ca28894443858db41cc92 to your computer and use it in GitHub Desktop.
Async Callbacks with Express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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