Async/Await & Express, Mocha etc.
Let's look how we can use Async/Await with common frameworks such as: Express.js, Mocha.js etc. The short of it is that: it's *really* easy. We just need to make sure that callbacks provided to the functions are prefixed with "async" so that we can use await
in the callbacks:
Express.js Examples:
app.get('/authors', async (req, res) => {
res.json(await model.getAuthors())
});
or a more elaborate example:
app.get('/health', async (req, res) => {
const someParam = req.header("someParam");
const check = await model.healthCheck(someParam);
if (!check) {
res.send(500, "Internal Server Error");
} else {
res.send(200, "OK");
}
});
Mocha Example:
const http = require('superagent');
describe('Get Authors', () => {
it('Success', async () => {
const params = {
// ... something
};
const response = await http.get('/authors', params);
assert.ok(response);
});
});
Pretty easy and elegant, isn't it?
Last updated
Was this helpful?