0

I have been pulling my hair out on this!

I am simply trying to hit an API endpoint which returns this exact JSON structure:

JSON

The code to retrieve this data is as follows:

let POSData = {

Users: {
        getByEmail: function(email){
            var firstName;
            var results = {};

            var url = userAPI.getUserURL+email;
            $.getJSON(url, function (posUser) {
              console.dir(posUser);
              firstName = posUser.data.firstName;

              results = {
                  firstName: firstName
              }

              alert("#1" + results.firstName);

            });

              alert("#2" + results.firstName);

              return results;
        }
    }

}

The Problem:

alert #1 DOES display the correct information.

alert #2 NEVER displays the correct information.

and finally,

the return statement NEVER has data.

WHY WHY WHY won't the correct value be returned? I just don't understand where I am going wrong.

Ideally, I would like this returned:

results = {

   firstName:  (value from json),
   lastName:   (value from json),
   profileImage: (value from json)
}

** It is quite obvious I am losing scope, but where??? **

Thanks for looking.

John S.
  • 504
  • 1
  • 3
  • 18
  • 3
    Asynchronous 101, You order a pizza and as soon as you make the order you try to eat it. It has yet been made or delivered. Has nothing to do with scope, it has to do with the fact the code in the complete callback has yet to run. – epascarello Oct 10 '19 at 21:10
  • Fairly new to the JS world, is that an answer, or a Book Title, or a class I need to take??? lol – John S. Oct 10 '19 at 21:12
  • You cannot expect to return a result when that result must still be produced (asynchronously). – trincot Oct 10 '19 at 21:12
  • linked dupe has plenty of examples. Modern approach is promises or await – epascarello Oct 10 '19 at 21:13
  • I certainly did not find a duplicate of this question here. Please remember, us new coders do not have the ability or skill set yet to view a question that may teach the same principal, or use a similar design pattern - and walk away with an answer. Sure, now thanks to these awesome SO users here, I now know to study up on asynchronous code - but ten minutes ago, I could have scrolled through a dozen pages of questions pertaining to asynchronous code, and not known that was what I was looking for. That aside, thanks for the help. – John S. Oct 10 '19 at 21:20

0 Answers0