react本机异步获取,未定义错误

react-native async fetch, undefined error

本文关键字:未定义 错误 获取 本机 异步 react      更新时间:2023-09-26

调用GetByUsername时,执行跳转到catch块但err是未定义的。api之所以能工作,是因为等效的promise风格代码.then().then(.done)能工作,但我希望用这种异步/等待风格写得更好。如何调试它?

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

编辑:通过查看react native的package.json,似乎使用的fetch实现是节点fetch和babeljs作为transpiler。

试试这个:

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

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