colonelsanders
colonelsanders

Reputation: 824

Ajax-assigned variable inaccessible after assignment

So, I have a script that fetches data from a SQL database and I'm trying to build a JS wrapper for it. I'm using the following functions to call that script and use information from the DB as soon as it's ready.

var User = function() {
    this.email = null;

    //Async call to get user values
    this.current(function(response) {
        this.email = response.email;

        //The value is assigned/usable at this point
    });
};

User.prototype.current = function(callback) {
    $.post("php/db_functions.php", {object: "CurrentUser"}).done(function(result) {
        callback(JSON.parse(result)[0]);
    });
};.

Everything seems to work fine, but if I try to access the value from the object after I've created it, it returns undefined, like so:

var me = new User();

//And then, way after the async call and when me.email should be defined
me.email //Returns undefined

Why can I use it in the callback, but not afterwards?

Upvotes: 0

Views: 69

Answers (2)

Witiko
Witiko

Reputation: 3407

In a function, the context variable this points to either the global window object or to undefined in the strict mode, unless specified otherwise by the caller. Therefore, you need to either capture the value of this in a local variable:

//Async call to get user values
var that = this;
this.current(function(response) {
    that.email = response.email;
});

or call the function in the desired context using either the call or the apply method:

User.prototype.current = function(callback) {
    var that = this;
    $.post("php/db_functions.php", {object: "CurrentUser"}).done(function(result) {
        callback.call(that, JSON.parse(result)[0]);
    });
};.

Also, as others have mentioned, there is no guarantee the AJAX request will have finished by the time the User contructor returns.

Upvotes: 2

TGH
TGH

Reputation: 39278

This is a timing bug since the variable is not assigned until the async call returns. You can't access email right away.

Upvotes: 1

Related Questions