How to store fetch response in javascript variable

Viewed 2802

sorry for the basic question. I was trying using fetch to get data from api and want to store that response into a javascript variable but its not working as I have expected My code-

async function fun() {
    var a = "initial";
    fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => res.json())
        .then(data => {
            a = data;
            console.log(a);
        })

    await console.log("Response => ", a);
}

Output - Response => initial

What is the correct way of doing this.

2 Answers

You may need to add await before fetch.

async function fun() {
  var a = "initial";
  await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => res.json())
    .then(data => {
      a = data;
      console.log(a);
    })

  console.log("Response => ", a);
}

You are doing more than you need to. Your fetch call should be returning the promise. Then when you want to access the data, you await the fun call, and can read the response

async function fun() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
}

const data  = await fun();

Alternatively, if you wanted to just use async/await you could do something like

const fun = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  return response.json()
}

await fun();
Related