typescript 等到 promise 完成并返回 true 或 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44322947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:36:10  来源:igfitidea点击:

Wait till the promise is finished and return true or false

javascriptangulartypescript

提问by M. Fish

I want to wait within a method till a promise return.

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

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 .....
}
......

this doesn't work. The method to call this loginOffline method just want to know if the login in was successful. I tried many things but nothing worked out.

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

Can anybody help. Thanks a lot Cheers

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

回答by Suraj Rao

You just have to chain the promise with another then. Call this way:

您只需要将 promise 与另一个then. 这样调用:

loginOffline('myname', 'mypassword').then(result =>{
   if(result){
     //do something
   }else{
     //do something else
   }
})

More on promise chaining

更多关于承诺链的信息

回答by Dhyey

You can use the Promiseobject like follows:

您可以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
    }
 })

回答by Duncan

The answer from @suraj is the correct one, simply use another .then()around the returned result, but an alternative is to use the await/asynckeywords to rewrite the code.

@suraj 的答案是正确的,只需.then()在返回的结果周围使用另一个,但另一种方法是使用await/async关键字来重写代码。

 public async loginOffline(username: string, password: string) {
    try {
      this.userLogin = await this.database.getItem('currentUser', 'login');
    } catch(e) {
      return false;
    }
    console.log(username + ' ' + this.userLogin.username + ' ' + password + ' ' + this.userLogin.password );
    return (
      username === this.userLogin.username &&
      password === this.userLogin.password);
  }

// This code must also be inside a function marked as 'async':
/********* call the method and descide what to do **************/
if(await loginOffline('myname', 'mypassword'){
// Do something.....
} else {
// Do something else .....
}
......

Note that every asyncfunction will automatically convert anything it returns into a Promise, so you have to use asyncall the way up the call tree. Or, if for some reason you don't want to make the caller asyncyou can just use thenon the result as before:

请注意,每个async函数都会自动将它返回的任何内容转换为 Promise,因此您必须一直使用async调用树。或者,如果由于某种原因你不想让调用者async你可以then像以前一样在结果上使用:

// If the caller cannot be marked `async`:
/********* call the method and descide what to do **************/
loginOffline('myname', 'mypassword').then(result => {
  if (result) {
  // Do something.....
  } else {
  // Do something else .....
  }
});
......

回答by jyothi

you can find the solution here:

你可以在这里找到解决方案:

function GetUserPemission(){
  return new Promise((resolve,reject)=>{
   getdata().then((data)=>{
      if(data){
            resolve(true);
      }else{
        resolve(false);
      }
    }).catch((error)=>{
            resolve(false);
    })
  })
}

function getdata(){
return new Promise((resolve,reject)=>{ setTimeout(()=>{resolve("Data")},100)})
}

GetUserPemission().then((data)=>{
        alert(data);
});