0

I am trying to store some data from an http request into a dictionary, when I return the dictionary however, it is always empty

function getUserData(id){
 var user = {}

 request('http://apis.scottylabs.org/directory/v1/andrewID/' + id, function (error, response, body) {
   if (!error && response.statusCode == 200) {
      data = JSON.parse(body);
    user.name = data.first_name + " " + data.last_name;
    if (Array.isArray(data.department)){
      user.dept = data.department[0];
    } else {
      user.dept = data.department;
    }
    user.level = data.student_level;
    user.class = data.student_class;
          // if i print user here it is correct
   }
 })
    // this is just returning {}
 return user;
}

How can I fix this?

Brad Chin
  • 11
  • 1

1 Answers1

0

The problem is your code is asynchronous and is not waiting for the API response to return the "User".

Use a callback function to return the user when the response comes back.

Something like this:

function getUserData (id, callback) { 
    var user = {};
    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {

          // if i print user here it is correct
          callback(user);
      }
    })
} 

The call would look like this:

getUserData(123, function (user) {
    // do something with the user data
})

If you were to console.log() each step of your current code it would look something like this:

get user data called.

empty user created

request made

empty user returned

response from request

Justin Herter
  • 590
  • 4
  • 17