Promises Tutorial by Irakli Nadareishvili
  • Introduction
  • Turning Callbacks Into Promises
  • Chain Parallel with Sequential
  • Conditions and Promises
  • Keeping Promise Chains Flat
  • Async and Await
  • Async/Await & Express, Mocha etc.
  • One More Thing (Go)...
  • One More Thing (Python)...
  • One More Thin (Nim)…
Powered by GitBook
On this page
  • Express.js Examples:
  • Mocha Example:

Was this helpful?

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?

PreviousAsync and AwaitNextOne More Thing (Go)...

Last updated 5 years ago

Was this helpful?