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

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

问题描述

我正在尝试将 JSON 保存到一个变量中,但似乎我不明白这里的所有内容.我让 JSON 以我喜欢的方式出现在控制台中,但是在我稍后再次尝试调用它之后,它只返回承诺.如何将 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天全站免登陆