John Masterson
John Masterson

Reputation: 1

Returning an JSON object from an API call using a function in Javascript

very basic question here (I'm a Javascript neophyte) that I oddly can't seem to find answered. I'm having trouble storing and displaying the result of a function that uses a fetch call. The code below spits out "undefined" in the console; any thoughts on what might be the problem?

function getApi() {
  var obj;

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

  return obj;
}

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

Upvotes: 0

Views: 1970

Answers (1)

Gwendal Vallée
Gwendal Vallée

Reputation: 31

The fetch method is asynchronous, so obj is undefined because your code is going to the next instruction without waiting the fetch. You 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://jsonplaceholder.typicode.com/posts/1")
        
      const obj = await response.json()
      
      return obj;
    }

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

Upvotes: 3

Related Questions