Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS await continues execution without resolved value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading