0

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);

2
  • 1
    You are trying to output a value that hasn't been fetched yet. Fetch takes some time to make the call and send back the result, and it's asynchronous, meaning that when you console.log your value, getApi() didn't finish yet, therefore didn't set the obj Commented May 7, 2021 at 21:27
  • 1
    Two solutions to fix the problem, good old callback that runs inside .then((data) => (obj = data));, or the less old school async/await method developer.mozilla.org/en/docs/Glossary/Callback_function - developer.mozilla.org/en/docs/Learn/JavaScript/Asynchronous/… Commented May 7, 2021 at 21:33

1 Answer 1

3

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);
})()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.