我正在制作一个使用 API 的货币转换应用程序。当我获取 API 时,data
变量具有我需要的 JSON。但是,当我将其存储到全局变量和 console.log
中时,输出为 null
。
代码:
const API_URL = 'SECRET';
let currency_json = null;
//Makes the request
async function getJSONdata(url) {
loading.style.display = '';
fetch(url)
.then(res => res.json())
.then(data => {
console.log(data); //Outputs the JSON. For some reason it gives null
currency_json = data;
})
.catch(err => console.log(err))
loading.style.display = 'none';
}
//Calls the function
getJSONdata(API_URL);
console.log(currency_json); //Outputs null
而且它也没有给出任何错误。我在另一个网站上阅读了另一个人的解决方案(在某处添加超时),问题是他们没有说在哪里或如何放置它。
最佳答案
您正在进行异步
调用。 Fetch 获取数据,但不能立即使用。
您需要等待数据可用。在 then
中,您等待它可用,这就是它工作的原因。
您可以使用 async/async,但似乎您是在模块级别进行调用,而这在模块级别不可用。您应该将代码移至 Promise 回调(then 方法)内部执行。
您所听说的setTimeout
是一种长轮询
形式,您可以像这样实现它
const longPollCallback = () => {
if (currency_json) {
console.log(currency_json)
} else {
setTimeout(longPollCallback, 500)
}
}
setTimeout(longPollCallback, 500)
但是你应该依赖then
、async/await
而不是长轮询。
关于JavaScript如何将Fetch数据存储到全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202940/