Return a Json Object from another function call

When we try to capture a value from called method we get undefined. The reason is that data hasn’t been fetched yet. Fetch takes some time to make the call and send back the result, and it’s asynchronous, Here is an example;

function getApi() {
  var obj;

  fetch("https://foo.apicode.com/posts/1")
    .then((res) => res.json())
    .then((data) => (obj = data));

  return obj;
}

let x = getApi();
console.log(x);

When we console.log the value, getApi() didn’t finish yet, therefore didn’t set the obj

The fetch method is asynchronous, so obj is undefined because the code is going to the next instruction without waiting the fetch. We can simply use async/await method that is a great way to make asynchronous calls because await will wait for the result before going to the next instruction.

async function getApi() {

      const response = await fetch("https://foo.apicode.com/posts/1")
        
      const obj = await response.json()
      
      return obj;
    }

(async() => {
   let x = await getApi();
   console.log(x);
})()

Resources

https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect