0

When calling GetByUsername, the execution jumps to catch block but err is undefined. The api is working because the equivalent promise style code .then().then().done() works, but I'd like to write in this async / await style better. How can I debug it ?

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

edit: By looking at react-native's package.json it seems that the fetch implementation used is node-fetch and babeljs as transpiler.

alfonsodev
  • 2,714
  • 2
  • 23
  • 30
  • How are you transpiling this, what promise library and what `fetch` polyfill are you using? What is wrong with `err` being undefined? What is the value of `err` if you use promise `.catch()`? – Bergi Nov 17 '15 at 14:38
  • Thanks, good points. for the first question I'v updated my question, "What is wrong with err being undefined?" That I don't know why it's failing. "What is the value of err if you use promise .catch()? " if I use promise .then().catch() , the code works well, nothing it's catch. – alfonsodev Nov 17 '15 at 15:48

2 Answers2

2

try this:

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

I found the problem was a misspelled variable, so I was returning a non existing variable, that cause the execution to end in the catch block with an undefined Error.

alfonsodev
  • 2,714
  • 2
  • 23
  • 30
  • I would expect ReferenceError on "response" variable, but what I get is "Uncaught ReferenceError: err is not defined" , so I focused on why err is not defined , not seeing that response was the one not defined in first place. – alfonsodev Nov 17 '15 at 18:44