0

I'm trying to return the result of an api call I've made but I keep on getting undefined as the output. here's the code:

function getProjects() {
  var message;
  gapi.client.dolapoapi.getProject({
    'appid': "test4"
  }).execute(function(resp) {
    if (!resp.code) {
      //get the response and convert it to a string 
      message = JSON.stringify(resp);
      //console.log(resp);  i get the correct output here
    }
    //console.log(message); i get the correct output here
  });
  //console.log(message);  it returns undefined. 
  return message;
}

I'm not sure what might be wrong. but what I'm trying to do is to return what's in the message variable after it's assigned here:

message = JSON.stringify(resp);
Iceman
  • 6,035
  • 2
  • 23
  • 34
Dolapo Toki
  • 362
  • 3
  • 13

1 Answers1

2

Pass a function as a callback and when the async operation is complete call the function with the data as parameter.

function getProjects(callback) {
  var message;
  gapi.client.dolapoapi.getProject({
    'appid': "test4"
  }).execute(function(resp) {
    if (!resp.code) {
      //get the response and convert it to a string 
      message = JSON.stringify(resp);
      //console.log(resp);  i get the correct output here
    }
    if(callback && typeof callback == "function") {
      callback(message);
    }
  });
}

getProjects(function(message) {
  //using a callback to get the data
  console.log(message);
});
Iceman
  • 6,035
  • 2
  • 23
  • 34