我正在尝试通过汇率来计算以美元为单位的近似价格。 我想在 console.log(currency) 中得到结果,但我只是在结束时未定义 请帮忙)
(async function() {
let date = new Date();
let currency = await searchCurrency();
await console.log(currency) // result expected
})();
function searchCurrency(){
if(!localStorage.currency||!JSON.parse(localStorage.currency).date==date.getDate()+'.'+date.getMonth())
{
return getCurrency(date);
} else {
console.log('LS the same!')
return JSON.parse(localStorage.currency).val;
}
}
function getCurrency(date){
var answer;
var xhr = new XMLHttpRequest();
var apiKey = "my_key";
var query = 'RUB' + "_" + 'USD';
var url =
"https://free.currconv.com/api/v7/convert?q=" +
query +
"&compact=ultra&apiKey=" +
apiKey;
xhr.open("GET", url);
xhr.onload = function () {
if (xhr.status != 200) {
console.log(`Error ${xhr.status}: ${xhr.statusText}`);
answer = 80;
} else {
console.log(`${xhr.response}`);
localStorage.setItem('currency', JSON.stringify({val: JSON.parse(xhr.response)[query], date: date.getDate()+'.'+date.getMonth()}));
answer = JSON.parse(xhr.response)[query];
}
};
xhr.send();
return answer;
}
UPD:感谢您的评论和类似问题。我将我的请求函数封装在一个如下面的 promise 中,它现在可以工作了 :) 如果将来对某人有用,请在此处发布。
(async function() {
let date = new Date();
let currency;
if (localStorage.currency&&JSON.parse(localStorage.currency).date==date.getDate()+'.'+date.getMonth()){
currency = JSON.parse(localStorage.getItem('currency')).val;
} else {
currency = await makeRequest(date);
localStorage.setItem('currency', JSON.stringify({val: currency, date: date.getDate()+'.'+date.getMonth()}))
}
await console.log(currency);
})();
function makeRequest(date) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://free.currconv.com/api/v7/convert?q=RUB_USD&compact=ultra&apiKey='secret_api_key');
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(JSON.parse(xhr.response).RUB_USD);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}