最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to put fetch data in a variable - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

The 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);
    } 
)
发布评论

评论列表(0)

  1. 暂无评论