首页 > 解决方案 > 如何将数据从 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 给了我未定义的变量。有人可以描述它是如何工作的吗?

标签: javascriptfetchfetch-api

解决方案


我假设您正在谈论的未定义控制台日志是最后一个。我复制了您的获取代码,并且效果很好。我认为正在发生的是最后一行(console.log(store))发生store 变量作为 fetch 行的一部分更新之前,因为 fetch 是异步的。

如果你需要对 fetch 的结果做一些事情,它要么必须嵌套在 promise 解析中(即,你重新定义的地方store),要么使用 async/await,使fetch代码同步工作,并在控制台登录之前运行结束。


推荐阅读