0

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Gardezi
  • 2,692
  • 2
  • 32
  • 62

2 Answers2

1

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())
}
Neall
  • 26,428
  • 5
  • 49
  • 48
  • 1
    Doesn't matter. `return await somePromise` inside an async funciton is as pointless as `return somePromise.then(value => value)`. – Thomas Jan 15 '18 at 14:33
  • 1
    @Thomas [Not in the OPs code](https://stackoverflow.com/a/43985067/1048572) – Bergi Jan 16 '18 at 04:00
0

The thing you have to understand is that once you step into the future ("I promise that this will eventually return a value"), you will never get back into the boring and safe world of synchronous step-by-step processing.

// It does not matter what you do inside this function or
// what you return. Because of the await keyword, this will
// **always** return a promise.
//
getCustomerById: async (id) => { /* ... */ }

The promise is a container, and you can pass that container around all you want. But to look inside the container you need to use a callback.

(Or use async/await, which is just syntactic sugar for .then. Under the hood it calls .then for you, with the remaining code left in your async function as the callback.)

So to get at the result, you need to wait for the promise to resolve. That leaves you with 2 choices: .then or await.

const apiKey = 'some_crazy_long_string_you_got_from_somewhere_safe'
const baseUrl = 'http://www.ready.buzlin.com/buzlinApp/customer'

// Let's show the object this is attached to, so we can 
// actually make calls to the function.
//
const customerQueries = {
  getCustomerById: async (id) => {
    const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`

    let response
    try {
      response = await fetch(url)
      return response.json()
    } catch (err) {
      // ... Properly handle error 
      // If you are not going to properly handle this error, then
      // don't catch it. Just let it bubble up.
    }
  }
}

// Or a cleaner looking alternative that is also more true to the
// underlying behavior by skipping all this `async/await` nonsense.
// 
const customerQueries2 = {
  getCustomerById: (id) => {
    const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`

    return fetch(url)
      .then(response => response.json())
      .catch(err => {
        // ... Properly handle error
      })
}


// Now to get at the result
// 

// Using .then
customerQueries.getCustomerById(27)
  .then(customer => {
    //
    // ... Do something with customer
    // 
  })

// Or using async/await
(async () => {
  const customer = await customerQueries.getCustomerById(27)
  //
  // ... Do something with customer
  // 
})()
skylize
  • 1,401
  • 1
  • 9
  • 21