等到承诺结束并返回true或false

M. *_*ish 3 javascript typescript angular

我想在一个方法中等待,直到承诺返回.

public loginOffline(username: string, password: string) {
    return this.database.getItem('currentUser', 'login').then(data => {
        this.userLogin = data;
        console.log(username + ' ' + this.userLogin.username + ' ' + password + ' ' + this.userLogin.password);
        if (username === this.userLogin.username && password === this.userLogin.password) {
            return true;
        } else {
            return false;
        }
    }).catch(err => {
        return false;
    });

}

/********* call the method and descide what to do **************/
if (loginOffline('myname', 'mypassword'){
    // Do something.....
} else {
    // Do something else .....
}
......
Run Code Online (Sandbox Code Playgroud)

这不起作用.调用此loginOffline方法的方法只是想知道登录是否成功.我尝试了很多东西,但没有成功.

任何人都可以帮忙.非常感谢干杯

Sur*_*Rao 9

你只需要将承诺与另一个联系起来then.这样打电话:

loginOffline('myname', 'mypassword').then(result =>{
   if(result){
     //do something
   }else{
     //do something else
   }
})
Run Code Online (Sandbox Code Playgroud)

更多关于承诺链


Dhy*_*yey 5

您可以Promise像下面这样使用对象:

public loginOffline(username: string, password: string) {
  return this.database.getItem('currentUser', 'login').then(data => {
      this.userLogin = data;
      console.log(username + ' ' + this.userLogin.username + ' ' + password + ' ' + this.userLogin.password );
      if (username === this.userLogin.username && password === this.userLogin.password) {
        return true;
      } else {
        return false;
      }
    }).catch(err => {
      return false;
    });   
}

loginOffline('myname', 'mypassword').then((result) => {
    if(result) {
      // true was returned
    } else {
      // false was returned
    }
 })
Run Code Online (Sandbox Code Playgroud)