javascript - 如何将数据从 fetch API 而非 ajax 存储到 var
问题描述
如何获取数据然后保存在变量中?
var store;
fetch('https://api.coindesk.com/v1/bpi/historical/close.json?start=2013-09-01&end=2013-09-05')
.then(function(response) {
return response.json();
})
.then(function(data) {
store = data;
console.log('Data is', store);
})
.catch(function(err) {
console.log('Unable to fetch the data', err);
});
console.log(store);
console.log 给了我未定义的变量。有人可以描述它是如何工作的吗?
解决方案
我假设您正在谈论的未定义控制台日志是最后一个。我复制了您的获取代码,并且效果很好。我认为正在发生的是最后一行(console.log(store)
)发生在store 变量作为 fetch 行的一部分更新之前,因为 fetch 是异步的。
如果你需要对 fetch 的结果做一些事情,它要么必须嵌套在 promise 解析中(即,你重新定义的地方store
),要么使用 async/await,使fetch
代码同步工作,并在控制台登录之前运行结束。
推荐阅读
- python - 在python中5秒后使用什么来启动警报
- c++ - 假设`std::ostream << T()`定义明确,如何为任何T打印std::optional <T>?
- dart - 在 dart 中的 do while 循环中切换大小写
- json - 如何使用提供的来自 REST API 的 JSON 在颤振中动态添加复选框/单选按钮组?
- scala - 在 Spark Scala 中分组后,在 df 中计算跨用户的元素
- php - 如何在 php laravel 中设置外键名称?
- python - 如何使用 setup.py 的命令单击设置 python 代码?
- javascript - React Native - 从原生 iOS 屏幕导航到 React Native 屏幕
- angular - ngClass 和 class 绑定有什么区别?
- python - PYTHON 中相同 sleep() 时间的随机变量总和