未捕获的TypeError:无法读取属性' get'未定义的错误

时间:2015-11-10 05:29:21

标签: javascript parse-platform

我正在尝试使用User类的电子邮件或用户名登录。但是,当我查询电子邮件并尝试执行

object.get("username") 

我收到上面的错误消息。奇怪的是,当我在调试器中测试辅助函数getUsername时,它可以正常工作

function getUsername(email) {
  var query = new Parse.Query(Parse.User);
  query.equalTo('email', email);
  query.first({
    success: function(object) {
      console.log(object.get("username"));
      return object.get("username");
    },
    error: function(user, error) {
      console.log("no email");
    }
  });
}


function signIn(usernameOrEmail, password) {

  //if not email sign in with username
  if (usernameOrEmail.indexOf("@") == -1) {
    Parse.User.logIn(usernameOrEmail, password, {
      success: function(user) {
        console.log("Logged in!");
      },
      error: function(user, error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }
  //query for username from email and signin
  else {
    var username = getUsername(usernameOrEmail);
    Parse.User.logIn(username, password, {
      success: function(user) {
        console.log("Logged in!");
      },
      error: function(user, error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }
}

1 个答案:

答案 0 :(得分:1)

query.first是一个异步函数。要使用它返回的值,您必须在success:回调函数中执行此操作。因此,将callbak传递给执行登录的getUsername

function getUsername(email, callback) {
  var query = new Parse.Query(Parse.User);
  query.equalTo('email', email);
  query.first({
    success: function(object) {
      if (object) {
        console.log(object.get("username"));
        callback(object.get("username"));
      } else {
        console.log("email not found");
      }
    },
    error: function(user, error) {
      console.log("no email");
    }
  });
}

function signIn(usernameOrEmail, password) {

  //if not email sign in with username
  if (usernameOrEmail.indexOf("@") == -1) {
    Parse.User.logIn(usernameOrEmail, password, {
      success: function(user) {
        console.log("Logged in!");
      },
      error: function(user, error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }
  //query for username from email and signin
  else {
    getUsername(usernameOrEmail, function(username) {
        signIn(username, password);
    });
  }
}