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.
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();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With