简体   繁体   English

如何从用作JS中的参数的匿名函数中分配外部作用域变量?

[英]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? 如何正确返回此函数的response ,以便对其进行定义? Just putting return response within the success: and error: callbacks doesn't return the outer logIn() function obviously, so I'm kind of stumped. 只是将return response放入成功和错误中:回调显然不会返回外部logIn()函数,因此我有些困惑。

alert(response);

is executing before 在执行之前

response = ...

because your Parse.User.logIn function does not run it's callback immediately. 因为您的Parse.User.logIn函数不会立即运行它的回调。 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. 为错误和成功设置单独的功能可能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM