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?
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?