如何将数据从 fetch API 而不是 ajax 存储到 var
how to store the data to a var from fetch API not ajax
如何获取数据然后保存在变量中?
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)
) 出现在 before store 变量已作为获取行的一部分更新,因为获取是异步的。
如果你需要对 fetch 的结果做一些事情,它要么必须嵌套在 promise 解析中(即你重新定义 store
的地方),要么使用 async/await,使fetch
代码同步工作,运行 在控制台日志最后。
如何获取数据然后保存在变量中?
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)
) 出现在 before store 变量已作为获取行的一部分更新,因为获取是异步的。
如果你需要对 fetch 的结果做一些事情,它要么必须嵌套在 promise 解析中(即你重新定义 store
的地方),要么使用 async/await,使fetch
代码同步工作,运行 在控制台日志最后。