2

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.

3 Answers 3

6

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Both of these give me the error: SyntaxError: await is only valid in async functions and the top level bodies of modules
You probably have something else going on there. As you can see, both of these functions are using the async keyword. Are you forgetting that part?
The await that is outside the function, still gives a SyntaxError.
5

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

1 Comment

Although technically correct, don't do this. This ain't good code. At least get rid of that nasty second then. like var a = await fetch(...).then(res => res.json());
0
let darth = fetch('https://jsonplaceholder.typicode.com/users')
let java = []
darth.then(res => res.json()).then((log) => java.push(log))
const user = java.flat().map(res => res)

This works on developer console on the chrome but not on visual studio code. Strange. I was able to fetch the data and put it into a const

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.