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



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

我有这个代码:

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文档指出

如果将Promise传递给等待表达式,它将等待承诺实现并返回已实现的价值。

Mozilla Doc

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

试试这个:

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

相关内容

最新更新