-3

I'm trying to get a value from a callback, but it returns an undefined value. Below is the code I'm using:

function getJSON(url, callback) {
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         if (callback) return callback(this.responseText);
      }
   };
   xhttp.open("GET", url, true);
   xhttp.send();
}

function getUserName() {
   getJSON("this is my url", function(resultJSON) {
      return JSON.parse(resultJSON).user[0].displayName;
   });
}

var userN = getUserName();
document.getElementById("username").innerHTML = "Hi " + userN;

I know this has been asked a billion times but I can't get it working the way I need with previous answers. The html element is still giving a "Hi undefined". Any thought or suggestion?

Ben
  • 1
  • 1
  • because there's no `return` statement in `getUserName()`, the `return` is in `function(resultJSON) {...}`, and because of time. The callback will be called "long" after `getUserName()` returns and this assignment is executed `var userN = getUserName();` – Thomas Jun 18 '19 at 08:35
  • You treated the callback in `getJSON` (even if the `return` is useless, you just need to call the `callback`), but not in `getUserName`. `getUserName` is an async function too, so it should also take a `callback` argument to do your actions when the data is there. – Kaddath Jun 18 '19 at 08:38

1 Answers1

0

function getJSON(url, callback) {
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         if (callback) return callback(this.responseText);
      }
   };
   xhttp.open("GET", url, true);
   xhttp.send();
}

function getUserName() {
   getJSON("https://my-json-server.typicode.com/typicode/demo/profile", function(resultJSON) {
      const userN = JSON.parse(resultJSON).name;
      document.getElementById("username").innerHTML = "Hi " + userN;
   });
}

getUserName();
<div id="username">Greetings</div>

You should write code for Hi + <userN> inside of 2nd parameter(callback function) of getJSON.

George Wang
  • 451
  • 2
  • 12