Home > Mobile >  NodeJS await continues execution without resolved value
NodeJS await continues execution without resolved value

Time:04-01

There are other questions similar to this one but not a single one of them helped me visualize my mistake.

I have this code:

function calc() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('block finished');
        }, 5000);
      });
}

async function asyncBlock() {
    let result = await calc();
    console.log('Result: '   result);
    return result;
}

app.get('/block', (req, res) => {
    let result = asyncBlock();
    console.log('Already returned the response without the result.');
    res.send(result);
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

The execution continues without the await response, giving me this output:

Example app listening on port 3000
Already returned the response without the result.
Result: block finished

Mozilla documentations states that

If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

Mozilla Doc

CodePudding user response:

Your call to AsyncBlock isn't asynchronous.

Try this:

app.get('/block', async (req, res) => {
    let result = await asyncBlock();
    console.log('Waited for the result');
    res.send(result);
})
  • Related