将提取的JSON保存到变量中 [英] Saving fetched JSON into variable

查看:75
本文介绍了将提取的JSON保存到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON保存到变量中,但是似乎我不了解这里的所有内容.我以自己喜欢的方式在控制台中一次显示了JSON,但是稍后尝试再次调用它后,它仅返回promise.如何将JSON保存到变量中,以便以后可以在JSON中使用对象?

I'm trying to get JSON saved into a variable, but it seems I don't understand everything here. I get JSON show up in console a once the way I like, but after I try to call it again later it only returns promise. How can I get JSON saved into a variable, so I could use objects in JSON later?

var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);

推荐答案

let jsondata;    
fetch(url).then(
        function(u){ return u.json();}
      ).then(
        function(json){
          jsondata = json;
        }
      )

基本上,一旦promise解析为实际数据,您就需要分配您的jsondata变量.目前,您正在将整个承诺分配给您的jsondata变量,而这并不是您想要的.

Basically you need to assign your jsondata variable once the promise resolves with the actual data. Currently, you're assigning the entire promise to your jsondata variable which is not what you want.

这篇关于将提取的JSON保存到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆