This seems like a straightforward google, but I can't seem to find the answer...
Can you pass in ES6 ES7 async functions to the Express router?
Example:
var express = require('express'); var app = express(); app.get('/', async function(req, res){ // some await stuff res.send('hello world'); });
If not, can you point me in the right direction on how to handle this problem ES7 style? Or do I just have to use promises?
Thanks!
For some time NodeJS has supported the async / await syntax, allowing you to avoid the many issues with Promises and Generators . However, out of the box, Express doesn't handle async route controllers very well.
To use async/await, you need to use the async keyword when you define a request handler. (Note: These request handlers are also called “controllers”. I prefer calling them request handlers because “request handlers” is more explicit). Once you have the async keyword, you can await something immediately in your code.
function asyncThing (value) { return new Promise((resolve) => { setTimeout(() => resolve(value), 100); }); } async function main () { return [1,2,3,4]. reduce(async (acc, value) => { return await acc + await asyncThing(value); }, Promise. resolve(0)); } main() . then(v => console.
In closing, utilizing async / await as your Express middleware implementation helps keep your code reusable, readable, and up-to-date with current coding conventions.
May be you didn't found results because async/await
is an ES7 not ES6 feature, it is available in node >= 7.6.
Your code will work in node. I have tested the following code
var express = require('express'); var app = express(); async function wait (ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms) }); } app.get('/', async function(req, res){ console.log('before wait', new Date()); await wait(5 * 1000); console.log('after wait', new Date()) res.send('hello world'); }); app.listen(3000, err => console.log(err ? "Error listening" : "Listening"))
And voila
MacJamal:messialltimegoals dev$ node test.js Listening undefined before wait 2017-06-28T22:32:34.829Z after wait 2017-06-28T22:32:39.852Z ^C
Basicaly you got it, you have to async
a function in order to await
on a promise inside its code. This is not supported in node LTS v6, so may be use babel to transpile code. Hope this helps.
Since ExpressJs 5, async functions are supported, and throw errors as expected
Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error
source
While it seems to work, it stops handling errors thrown inside the async function, and as a result, if an error is not handled, the server never responds and the client keeps waiting until it timeout.
The correct behavior should be to respond with a 500 status code.
const router = require('express-promise-router')(); // Use it like a normal router, it will handle async functions
const asyncify = require('express-asyncify')
app
objectReplace var app = express();
with
var app = asyncify(express());
router
objectsReplace var router = express.Router();
with
var router = asyncify(express.Router());
You only need to apply the asyncify
function in the objects where you set the routes directly
https://www.npmjs.com/package/express-asyncify
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With