【问题标题】:Timeouts with async await in Node.js not working?Node.js 中异步等待的超时不起作用?
【发布时间】:2020-07-04 02:23:12
【问题描述】:
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函数返回的promise。将 display 函数从 async 更改为返回新承诺的常规函数​​,该承诺在特定秒数后解决。

标签: node.js asynchronous promise async-await


【解决方案1】:

您应该更改display 函数,使其仅在执行setTimeout 调度的函数后才解析promise,例如:

function display(name) {
  return new Promise(resolve => {
    setTimeout(function () {
      console.log("displaying "+name)
      returnBody += name + " ";
      resolve(1);
    }, name + "000");
  })
}

【讨论】:

  • @horusoftheblackflame 欢迎您!如果您觉得有帮助,请接受并投票支持答案,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 2017-12-21
  • 2019-01-13
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
相关资源
最近更新 更多