-1

I have a very simple question but it has been bouncing all over my head how to handle this. I've been using this API that requires a callback function to capture the values, and i'm having issues in returning the output of the function to other functions that i'm using on my project.

For example:

function a() {
var callback = function(e) {
  var id = e.data.responseData.Id;
};
Api.getId(callback);    
}

If i try to call the variable id, it will give me undefined so i'm assuming that the id value is not being passed available globally.

On the other side if i run something like this:

function a() {
    var callback = function(e) {
      var id = e.data.responseData.Id;
      console.log(id);
    };
    Api.getId(callback);    
    }

It will return me on the console correctly the value of id.

Any ideas on what i'm missing here?

Thanks once again.

Rafa

Rafa
  • 21
  • 1
  • 5
  • Your question is not clear enough. There is no return statement in the entire code example you have given. Which function should return something? – vinit Nov 05 '16 at 18:55
  • Is suppose to return the id value. I've tried adding the "return id" but also didn't work. Essentially i want to use id on other functions outside of that scope. – Rafa Nov 05 '16 at 19:00
  • You can't return a value asynchronously. If you have to use `id` in other functions, call those functions from the callback function passing `id` as an argument. Example - `var callback = function(){ id = getId(); foo(id);}` – vinit Nov 05 '16 at 19:21

1 Answers1

0

you need to return variable "id" in function:

function a() {
var callback = function(e) {
  var id = e.data.responseData.Id;
  return id;
};
Api.getId(callback);    
}
Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28