【问题标题】:react-native async fetch, undefined errorreact-native async fetch,未定义的错误
【发布时间】:2016-02-18 22:36:57
【问题描述】:

调用GetByUsername时,执行跳转到catch块 但错误是未定义的。该 api 正在工作,因为等效的 promise 样式代码 .then().then().done() 有效,但我想更好地以这种 async / await 样式编写。我该如何调试它?

var cli = {
    GetByUsername: async function(username) {
       try {
         let resposne = await fetch(`http://api.example.com?username=${username}`);
         return response;
       } catch(err) {
         debugger;
       }
    }
}

编辑: 通过查看 react-native's package.json,似乎使用的 fetch 实现是 node-fetchbabeljs 作为转译器。

【问题讨论】:

  • 你是如何编译这个的,你使用的是什么 promise 库和 fetch polyfill? err 未定义有什么问题?如果你使用promise .catch()err 的值是多少?
  • 谢谢,好点。对于第一个问题,我更新了我的问题,“错误未定义有什么问题?”我不知道为什么它失败了。 “如果你使用 promise .catch(),err 的价值是什么?”如果我使用 promise .then().catch(),代码运行良好,没有任何问题。

标签: javascript asynchronous async-await react-native ecmascript-2016


【解决方案1】:

试试这个:

const response = await fetch(`http://api.example.com?username=${username}`);
const jsonData = await response.json();
// then you can use jsonData as you want

【讨论】:

    【解决方案2】:

    我发现问题是一个拼写错误的变量,所以我返回了一个不存在的变量,这导致执行以未定义的错误在 catch 块中结束。

    【讨论】:

    • 我希望“response”变量上有 ReferenceError,但我得到的是“Uncaught ReferenceError: err is not defined”,所以我专注于为什么 err 没有定义,没有看到响应是一个没有首先定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多