2

I am calling this function, assigning the result to a variable in the callback and then logging the result, but I keep getting undefined.

var id;
test.getID(function(result) {
    id=result;
});
console.log(id);

If I change it to the code below, then I can see the id logged.

var id;
test.getID(function(result) {
    id=result;   
    console.log(id);
});

Do you know what I can do to be able to access the result of the getID function?

Arun V
  • 590
  • 6
  • 20
  • 1
    it's probably because you're logging `id` immediately. The callback you're passing to `getID` is probably getting executed *after* your `console.log`. That's why the second one works...you're logging it after the callback has done it's work. – Jonathan Beebe Aug 23 '11 at 20:42
  • It's not about scope, it's about "timing", I guess that `test.getID` is doing something asynchronous, and when you try to log the value of `id`, it hasn't yet been assigned... Work on the callback, or call a separate function, passing your `result`... – Christian C. Salvadó Aug 23 '11 at 20:43
  • Does `test.getID` make an Ajax request? – Peter C Aug 23 '11 at 20:55
  • I think test.getID might be making an Ajax request. – Arun V Aug 23 '11 at 21:02

2 Answers2

1

The getID function will need to invoke its parameter before you will see id change.

Since you do not provide its implementation, let's assume it's something like this. Pay close attention to the implementation of getID, it takes a function as the parameter, f, and then invokes it. This is when id will be set.

var id;
var test = { 
    getID: function(f){
        var result = 666; //assume result comes from somewhere
        f(result); //Note: this is where your function is getting invoked.
    }
};

test.getID(function(result) {
    id = result;
});

console.log(id); //prints 666
wsanville
  • 37,158
  • 8
  • 76
  • 101
0

A closure would work for you as well:

var id,
test = {
  getID: function (id) {
    this.id = id;
  },
  id: -1
};

test.getID((function(result) {
    id=result;
    return id;
})(78));
console.log(id);
Joe
  • 80,724
  • 18
  • 127
  • 145