【问题标题】:react typescript return value with asynchronous functions用异步函数反应打字稿返回值
【发布时间】:2021-04-10 14:41:26
【问题描述】:

我不明白这里有什么问题。 我收到消息:TS2366:函数缺少结束返回语句并且返回类型不包括“未定义”。

我有一个承诺,我在任何地方都会给出数字类型的回报。

有人知道吗?

export async function setAdress(newAdress: IAdress):Promise<number> {

 try {
    await axios.post<IAddAdressResult>('http://localhost:8090/rest/web/api/addAdress', newAdress)
        .then(res=> {
            if (res.data && (res.data as IAddAdressResult)) {
                alert('Address written successfully. ' + res.data.ADRESSID.toString());
                return res.data.ADRESSID
            } else return 0
        })
        .catch(error => {
            alert('Error writing the address ' + error);
            return 0

        });

 } catch (e) {
     return 0
 }

}

【问题讨论】:

  • 您不返回任何内容,甚至不分配要返回的等待值。不要混合使用 async/await 和 .try/.catch 语法。

标签: reactjs typescript promise async-await axios


【解决方案1】:

你需要返回整个 Promise 链。照原样,setAdress 函数不返回任何内容。

您还应该考虑将拼写修正为address(拼写错误是编程中常见的错误来源),如果您还有.catch,则try/catch 是多余的。

export async function setAdress(newAdress: IAdress): Promise<number> {
    return axios.post<IAddAdressResult>('http://localhost:8090/rest/web/api/addAdress', newAdress)
        .then(res => {
            if (res.data && (res.data as IAddAdressResult)) {
                alert('Address written successfully. ' + res.data.ADRESSID.toString());
                return res.data.ADRESSID
            } else return 0
        })
        .catch(error => {
            alert('Error writing the address ' + error);
            return 0

        });
}

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2021-08-24
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2020-05-09
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多