【问题标题】:Async await Axios no response异步等待 axios 无响应
【发布时间】:2020-12-09 16:13:11
【问题描述】:

我有一个简单的方法可以让 Axios 调用 API。调用该方法不会返回任何内容,没有日志,也没有错误消息。

async disable(product: Product): Promise<void> {

    try {
        const response = await this.axios.put(`products/update`, {
                data
            }).then(value => {
            return value.data;
        }).catch(error => {
            console.log(`error: ${JSON.stringify(error)}`);
        });

        return response;
    } catch (e) {
        console.log(e);
    }
}


await disable(product)

【问题讨论】:

  • 您正在混合使用 promise awaitthen().catch() 语法。从未尝试过 - 但这可能已经是问题所在了。
  • 这不是一件漂亮的事情,但应该不成问题。 @madflow
  • 如果您实际打印返回值,它会显示什么? console.log(await disable(product))
  • @GuyIncognito 什么都没有

标签: javascript typescript axios


【解决方案1】:

您的代码有一些问题:

  • 您的返回类型不应为 void,因为您要返回某种数据
  • 并非所有代码路径都返回结果
  • 如果您没有收到错误,调用 await disable(product) 将不会打印任何内容
  • 应在正确的级别上进行日志记录
  • 应尽可能避免混合使用 Promise 和 async/await 语法
  • 另外,我不知道您的示例中的 data 来自哪里。我假设它是某个东西的占位符,但如果不是,而您想发送产品,则应该在其中写下它

我建议你这样重写:

async disable(product: Product): Promise<any> { // or the type that you expect
    try {
        const response = await this.axios.put(`products/update`, {data}); // Dont mix Promise and async/await syntax, if avoidable

        return response.data; // return the response data directly
    } catch (e) {
        console.error(`error: ${JSON.stringify(error)}`);
        throw e; // rethrow error or return null, if the request failed
    }
}


const result = await disable(product);
console.log(result); // Print the result, to see what you are getting

另外,下次有一些技巧可以解决这样的问题:

  • 如果它在浏览器中,请检查网络选项卡以查看是否正在发送请求以及响应是什么
  • 尽可能多地记录日志或使用调试器查看代码的去向

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 2019-01-04
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2017-10-18
    相关资源
    最近更新 更多