node.js - Node.js 中异步等待的超时不起作用?
问题描述
app.get('/testAsync', asyncHandler(async function (req, res,next) {
//res.send('We test async here')
async function display(name) {
setTimeout(function () {
console.log("displaying "+name)
returnBody += name + " ";
return 1
}, name + "000");
}
async function send()
{
console.log("sending "+returnBody)
res.send(returnBody)
//returnBody="";
console.log('all done!')
return 'alldone';
}
const getInfo = async () => {
// failed attemp 1
// display("1")
// display("2")
// display("3")
// display("4")
// display("5")
//failed attempt 2
// display(1).then(
// display(2)).then(
// display(3)).then(
// send()
// )
//failed attempt 3
// await display(1)
// await display(2);
// await display(3);
send(await display(1),await display(2),await display(3));
//await send(display1,display2,display3)
}
await getInfo();
}))
理想情况下,我希望我的控制台阅读:
- 显示 1
- 显示 2
- 显示 3
- 发送
- 全部完成!
相反,控制台正在显示
- 发送
- 全部完成!
- 显示 1
- 显示 2
- 显示 3
我究竟做错了什么?不确定它是否重要或有帮助,但超时背后的想法是模仿 sql 执行。
解决方案
您应该更改display
函数,以便它仅在setTimeout
执行调度的函数后才解析承诺,例如:
function display(name) {
return new Promise(resolve => {
setTimeout(function () {
console.log("displaying "+name)
returnBody += name + " ";
resolve(1);
}, name + "000");
})
}
推荐阅读
- karate - 空手道:问号被编码为路径的一部分
- r - 强制绘图在中间有“0”,并且在 R 中为 + 和 - 值等量缩放
- c# - 如何使用数据库优先更改连接字符串
- ios - 转换后获取不正确的日期格式
- python - 如何解决 Jupyter Notebook 中的内核错误?(win64)
- postgresql - 如何动态地将列添加到 PostgreSQL SQL where 子句
- kubernetes - 使用 kubectl 设置镜像拉取策略
- python - 如何使用 hvplot 绘制堆积条形图?
- embedded - ADXL345 读取问题
- git - 无法通过代理 url 推送到 gitlab