Saving fetched JSON into variable(将获取的 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 保存到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将获取的 JSON 保存到变量中


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01