user1203497
user1203497

Reputation: 517

Node.js/Express: async function inside middleware?

I was wondering how you make async functions to work inside middleware? Normally await in front of the function would get the job done, but in middleware it seems not working.

index.js:

const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
    console.log('3')
})

middleware/bob.js:

async function test(){
    setTimeout(() => {
        console.log('1')
    }, 2000);
}

module.exports = function(channels){
   return async(req, res, next) =>{
        await test();
        console.log('2')

        next();
    }
}

When I run this code. It will write into console: 2 3 1

Upvotes: 4

Views: 1155

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

await awaits for a promise. A promise that is returned from test function is resolved immediately. async function shouldn't be aware of setTimeout of any asynchronous processes that happen inside of it except promises that are chained with await or return.

If the intention is to delay it, it should be:

async function test(){
    await new Promise(resolve => setTimeout(resolve, 2000));
    console.log('1')
}

Upvotes: 5

Related Questions