【问题标题】:How to return value in async await functions?如何在异步等待函数中返回值?
【发布时间】:2020-08-19 19:24:56
【问题描述】:
const getNetwork = async () => {
        const status = await Network.getStatus();
        setStatus(status.connected);
        console.log(networkStatus);
        if (status.connected)
            return true;
        else
            return false;
}

如何从 getNetwork 函数中取回值?

【问题讨论】:

  • await 你对 getNetwork() 的调用 - 并等待 that 函数,依此类推。 async/await 对程序具有“病毒式”影响,如果您没有做好准备,可能会引起很大的头痛。

标签: reactjs typescript ionic-framework


【解决方案1】:

与处理任何其他基于承诺的函数的方式几乎相同

const res = await getNetwork();

getNetwork().then((res) => {
  // get response, handle the rest 
})

【讨论】:

    【解决方案2】:

    异步操作返回 Promise 对象。如果您从示例中的函数返回 Promise 并将其直接传递给变量,则其类型将是 Promise。因此,您将能够对其调用 then() 和 catch() 方法。

    const res = getNetwork();
    res.then(
      (responseData) = doSomething();
    )
    

    但是如果你用await前缀存储返回值,那么它会返回解析后的数据

    const res = await getNetwork();
    console.log(res); // res will be equal responseData above
    

    但是你必须小心错误,如果它抛出错误,你的代码就会崩溃。我个人更喜欢将这个过程封装在一个 try-catch 块中,如果我发现一个错误,我会返回一个空值。下面的示例代码

    async getResponse(): Promise<object> { // object can be changed with your response type
      try {
        const res = await getNetwork();
        return res;
      } catch (e) {
        return null;
      }
    }
    

    【讨论】:

    • @Anıl 如何转换为 TSX 脚本:Promise => const getNetwork = async () => { }??
    • @BryantTang,抱歉,我不了解 .tsx 文件/脚本
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2013-07-24
    • 2020-03-13
    • 2011-03-04
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多