Mike Crittenden
Mike Crittenden

Reputation: 5917

How to assign an outer scoped variable from within an anonymous function being used as a param in JS?

(Couldn't think of any simpler way to write the title for this, but the code should explain it).

Here's my code:

function logIn(email, password) {
   var response;
   Parse.User.logIn(email, password, {
     success: function(user) {
       response = [true, user];
     },
     error: function(user, error) {
       response = [false, "Error: " + error.code + " " + error.message];
     }
   });
   return response; // still undefined :(
}

How can I correctly return response for this function so that it's defined? Just putting return response within the success: and error: callbacks doesn't return the outer logIn() function obviously, so I'm kind of stumped.

Upvotes: 0

Views: 185

Answers (1)

Eric
Eric

Reputation: 97601

alert(response);

is executing before

response = ...

because your Parse.User.logIn function does not run it's callback immediately. If it did, then you wouldn't have a problem.

function logIn(email, password, callback) {
   Parse.User.logIn(email, password, {
     success: function(user) {
       callback([true, user]);
     },
     error: function(user, error) {
       callback([false, "Error: " + error.code + " " + error.message]);
     }
   });
}

logIn(..., ..., function(response) {

});

At this point though, it becomes questionable if the function servers any purpose. Having separate functions for error and success is probably better.

Upvotes: 3

Related Questions