【问题标题】:simple async function in javascriptjavascript中的简单异步函数
【发布时间】:2019-01-20 20:28:35
【问题描述】:

我正在使用 async/await 和下面的代码,在响应 const 中的 setTimeout 在 5 秒后完成之前,响应不应该为空或 null 吗?并且不应该响应返回 xyz 而不是 1?

async function test() {
  try {
    const response = await setTimeout(
      function() { 
        const obj = {};
        obj.text = "xyz";
        console.log('should console log after 5 seconds')
        return obj;
      }, 
    5000)

    if (response) {
      console.log(`response is ${response}`)
      console.log(`response.text is ${response.text}`)
    }
  } 
  catch(err) {
    console.log(err)
  }
}

test();

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:

    你必须设置一个 Promise 来等待 setTimeout()。

    async function test() {
    try {
        const response = await new Promise((resolve) => {
            setTimeout(
                function() {
                    const obj = {};
                    obj.text = "xyz";
                    console.log('should console log after 5 seconds')
                    return resolve(obj);
                },
                5000)
        });
    
        if (response) {
            console.log(`response is ${response}`)
            console.log(`response.text is ${response.text}`)
        }
    }
    catch(err) {
        console.log(err)
    }
    }
    
    test();

    【讨论】:

    • 我认为 async 的全部意义在于使用起来比 promise 更干净?
    • await 运算符用于等待Promise。您必须在 async 函数中使用 await
    【解决方案2】:

    要使您的代码按预期工作,您需要将设置的超时包装在一个承诺中。检查sn-p。 setTimeout 不包装在 promise 中,立即返回 value,即计时器的 ID 值。

    async function test() {
      try {
        const response = await new Promise(function(resolve, reject) {
          setTimeout(
            function() {
              const obj = {};
              obj.text = "xyz";
              console.log('should console log after 5 seconds')
              resolve(obj);
            },
            5000)
        })
    
        if (response) {
          console.log(`response is ${response}`)
          console.log(`response.text is ${response.text}`)
        }
      } catch (err) {
        console.log(err)
      }
    }
    
    test();

    【讨论】:

    • 我认为 async 的全部意义在于使用起来比 promise 更干净?
    • 是的,但 setTimeout 不返回承诺。它返回定时器的 ID 值。检查w3schools.com/jsref/met_win_settimeout.asp
    • 我怎么知道什么会或不会返回它自己的承诺?
    • 控制台记录返回值。如果它是一个承诺,它将打印承诺。或者,检查返回值是否具有 then 属性。如果是这样,那就是一个承诺
    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 2017-08-01
    • 2022-01-01
    • 2019-04-18
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多