NodeJS await 在没有解析值的情况下继续执行

NodeJS await continues execution without resolved value

还有其他类似的问题,但没有一个能帮助我想象我的错误。

我有这个代码:

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}`)
})

在没有等待响应的情况下继续执行,给我这个输出:

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

Mozilla 文档指出

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

Mozilla Doc

您对 AsyncBlock 的调用不是异步的。

试试这个:

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