我正在制作使用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
它也不给出任何错误。而且我已经在另一个网站上阅读了另一个人的解决方案(要在某处添加超时),问题是他们没有说要在哪里放置它或如何放置它。
答案 0 :(得分:3)
您正在拨打async
。提取会获取数据,但无法立即使用。
您需要等待数据可用。在then
中,您等待它可用,这就是为什么它起作用的原因。
您可以使用async / async,但似乎您是在模块级别进行调用的,因此那里不可用。您应该将代码移到从promise回调(then方法)内部执行。
您听说过setTimeout
是long polling
的一种形式,您可以像这样实现它
const longPollCallback = () => {
if (currency_json) {
console.log(currency_json)
} else {
setTimeout(longPollCallback, 500)
}
}
setTimeout(longPollCallback, 500)
但是您应该依靠then
,async/await
而不是长时间的轮询。