Express: does express support async and await?

Created on 25 Feb 2020  Â·  2Comments  Â·  Source: expressjs/express

dose express support async and await for next function?

this is my code:

const express = require('express');
const app = express();

async function sleep(timeout) {
    return new Promise((resolve) => {
        setTimeout(resolve, timeout);
    });
}

app.use(async (req, res, next) => {
    await sleep(100);
    console.log("router prefix");
    await sleep(100);
    await next();
    await sleep(100);
    console.log("router post");
    await sleep(100);
});

app.use(async (req, res, next) => {
    await sleep(100);
    console.log("log prefix");
    await sleep(100);
    await next();
    await sleep(100);
    console.log("log post");
    await sleep(100);
});

app.get('/', async (req, res) => {
    await sleep(100);
    console.log("process prefix");
    await sleep(100);
    res.send({});
    await sleep(100);
    console.log("process post");
    await sleep(100);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

the output is that:

router prefix
log prefix
router post
process prefix
log post
process post

rather than :

router prefix
log prefix
process prefix
process post
log post
router post

is it a bug, or something wrong with my code?

question

All 2 comments

Your example is how the Koa web framework works. The next() function in Express does not return a promise.

Purely out of interest, what is the reason v5 doesn’t return a promise from ‘next’, are there technical / performance challenges or is it simply a design decision?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gaurav5430 picture gaurav5430  Â·  3Comments

zackarychapple picture zackarychapple  Â·  3Comments

dmaks9 picture dmaks9  Â·  3Comments

afanasy picture afanasy  Â·  3Comments

ZeddYu picture ZeddYu  Â·  3Comments