我实现了以下代码段:
var tmpString = null;
this.restProvider.validateUser(this.registerCredentials.email, this.registerCredentials.password)
.then(data => {
tmpString = JSON.stringify(data);
});
console.log(tmpString);
但是,尽管数据不为null,但是控制台会在短时间内将输出null值并将tmpString设置为正确的值。我该如何解决这个问题?谢谢
真正的功能是:
registerNewUser()
{
var tmpString = null;
this.restProvider.validateUser(this.registerCredentials.email, this.registerCredentials.password)
.then(data => {
tmpString = JSON.stringify(data);
});
console.log(tmpString);
if(tmpString == "false")
{
return false;
}
else
{
this.registerCredentials.email = JSON.parse(tmpString).email;
this.registerCredentials.password = JSON.parse(tmpString).password;
this.email = JSON.parse(tmpString).email;
this.password = JSON.parse(tmpString).password;
}
return this.email + this.password;
}
我用它
public login() {
this.showLoading();
this.registerNewUser();
if(this.email == "false" && this.password == "false")
{
this.showError("Access Denied");
}
else
{
this.auth.login(this.registerCredentials);
this.showError("Access Permit");
}
}
我决心这样做
registerNewUser()
{
var tmpString = null;
this.restProvider.validateUser(this.registerCredentials.email, this.registerCredentials.password)
.then(data => {
tmpString = JSON.stringify(data);
if(tmpString == "false")
{
this.showError("Access Denied");
}
else
{
this.registerCredentials.email = JSON.parse(tmpString).email;
this.registerCredentials.password = JSON.parse(tmpString).password;
this.email = JSON.parse(tmpString).email;
this.password = JSON.parse(tmpString).password;
this.auth.login(this.registerCredentials);
this.showError("Access Permit");
}
});
}
但这是正确的解决方案吗?
答案 0 :(得分:3)
考虑以下代码(带有行号的注释):
var tmpString = null; // 1
this.restProvider.validateUser(this.registerCredentials.email, this.registerCredentials.password)
.then(data => {
tmpString = JSON.stringify(data); // 2
});
console.log(tmpString); // 3
执行顺序为:
这是因为到达第3行时,异步请求尚未完成。因此,为了正确打印tmpString
,请将console.log(tmpString);
移动到回调中的第2行之后(响应到达时),如下所示:
var tmpString = null; // 1
this.restProvider.validateUser(this.registerCredentials.email, this.registerCredentials.password)
.then(data => {
tmpString = JSON.stringify(data); // 2
console.log(tmpString); // 3
});