0

Could you help me cope with the async request. My task is to organize a function to get a city name by IP and return it. But I stuck with this asynchrony.

My code:

async function get_city(){
    // Get city name by IP. 

    const http = new XMLHttpRequest();
    const url='https://api.sypexgeo.net/json/';
    http.open("GET", url);
    http.send();

    var response_json = await JSON.parse(http.responseText);
        return response_json["city"]["name_ru"];    
}

I get this error:

Promise {<rejected>: SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at get_city (http://vi…}
?utm_replace=ViarVizualizatorArhiva_TR:645 
?utm_replace=ViarVizualizatorArhiva_TR:591 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at get_city (?utm_replace=ViarVizualizatorArhiva_TR:591)
    at replacer (?utm_replace=ViarVizualizatorArhiva_TR:639)
    at ?utm_replace=ViarVizualizatorArhiva_TR:649

How to cope with this error?

Michael
  • 4,273
  • 3
  • 40
  • 69
  • Don't use var, change it to const/let. Why are you using await with JSON.parse? What inside your http.responseText? Do you have a try/catch block inside your app? – Nikolay Vetrov Jan 24 '19 at 22:55
  • That `await` makes no sense. Currently you are calling `JSON.parse` before the response arrived, and `responseText` is still an empty string. You need to properly promisify XHR first, so that you can wait for it. – Bergi Jan 24 '19 at 22:57

1 Answers1

0

You need to listen for a load event on the request.

http.addEventListener("load", function () {
  console.log(JSON.parse(http.responseText));
});

To build a Promise out of it, you can resolve inside of the load event.

function get_city() {
  return new Promise(function(resolve) {
    const http = new XMLHttpRequest();
    http.addEventListener("load", function () {
      resolve(JSON.parse(http.responseText));
    });
    http.open("GET", 'https://api.sypexgeo.net/json/');
    http.send();
  });
}

To use this function, you can call it with await.

async function() { await get_city(); }
Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99