1

I'm trying to get the exchange rates to calculate approximate prices in dollars. I want to get result in console.log(currency), but I just got undefined over an over Pls help)

(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: Thanks for comments and similar questions. I wrapped my request function in a promise like below and it's working now :) Posting that here if it'll be useful for someone in future.

(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();
    });
}
rkosolapov
  • 11
  • 4
  • `console.log` doesn't return anything. `await` needs a promise. You can't await `searchCurrency()` because it doesn't return a promise. – Thomas Sablik Feb 12 '21 at 14:15
  • @deceze - How do that question's answers help here? – T.J. Crowder Feb 12 '21 at 14:16
  • @TJC Because it's the same classical problem in `getCurrency`'s `xhr.onload` and `return answer`…?! – deceze Feb 12 '21 at 14:17
  • 2
    Neither `getCurrency` nor `searchCurrency` returns a promise, so using `await` on them won't do anything useful. See [this question's answers](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) for how to wrap a callback API in a promise, but rather than doing that, I suggest using [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), which is already promise-enabled. Just beware of the footgun in the API I cover [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder Feb 12 '21 at 14:19
  • @deceze - The fundamental thing here is not understanding that `await` doesn't solve that problem. – T.J. Crowder Feb 12 '21 at 14:19

0 Answers0