首页 > 解决方案 > 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();



}))

理想情况下,我希望我的控制台阅读:

相反,控制台正在显示

我究竟做错了什么?不确定它是否重要或有帮助,但超时背后的想法是模仿 sql 执行。

标签: node.jsasynchronouspromiseasync-await

解决方案


您应该更改display函数,以便它仅在setTimeout执行调度的函数后才解析承诺,例如:

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

推荐阅读