I have a code that results undefined
whenever I try fetch results into a variable
var data;
fetch('./js/samplejson.json')
.then((res) => res.json())
.then(output => {
var data = output;
}
)
console.log(data);
How can I get a result of
[1, 2, 3]
inside data variable
I have a code that results undefined
whenever I try fetch results into a variable
var data;
fetch('./js/samplejson.json')
.then((res) => res.json())
.then(output => {
var data = output;
}
)
console.log(data);
How can I get a result of
[1, 2, 3]
inside data variable
Share Improve this question edited Jan 22, 2018 at 10:00 Klt asked Jan 22, 2018 at 9:52 KltKlt 2091 gold badge3 silver badges10 bronze badges 1- @MichaelGeary yup.thats true.he is declared the data at the top.like [1,2,3] earlier – zabusa Commented Jan 22, 2018 at 10:04
2 Answers
Reset to default 6The fetch()
call is asynchronous. It returns before the data es back from the server. When you try to access the data after the call, you're trying to access it before the server has responded.
You need to handle that data inside the callback, or in a function called from that callback. In other words, where you do var data = output;
, don't do that. It won't help to remove the var
so the code sets the global data
variable as suggested in a ment. The problem isn't scope, it's timing. Process the output
data right there inside the callback, or call another function and pass output
to it.
You can get data from log here.
fetch('./js/samplejson.json')
.then((res) => res.json())
.then(output => {
var data = output;
console.log(data);
}
)