javascriptjsonasync-awaitecmascript-2017

not getting correct data from promise


Hello guys I'm using await keyword to wait for the async call to return. My url is a get url so if I call it from my browser a json is returned. The problem is when I try to get data from my code it returns me a promise but I can't figure out how to get the data response out of that promise

getCustomerById: async (id) => {

    try {
      const response = await fetch("http://www.ready.buzlin.com/buzlinApp/customer/getCustomerById.php?k=xxx&id=xxx");
      // console.log("Response Returned: "+ JSON.stringify(response));
      // resolve(response.json());
        debugger;
      return response.json();
    } catch (err) {
    }
  }

Now this is what json.reponse() returns me

enter image description here

Can somebody tell me what is it that I'm doing wrong. Thanks


Solution

  • fetch(...) returns a promise, and you are unwrapping that promise by using await, so that's good. But response.json() also returns a promise, so you probably want to use await on that also:

    const response = await fetch(url)
    const data = await response.json()
    debugger
    return data
    

    Note: as Thomas points out in a comment - if you're just returning response.json() in an async function, you shouldn't unwrap it - it will just get wrapped in another promise anyway. It's only because you're entering the debugger and trying to inspect it that you need to get the value out of the promise. In fact, your function should probably look more like this:

    getCustomerById: (id) => {
      const url = 'http://example.com/customer/' + id
      return fetch(url).then((response) => response.json())
    }