Typescript returning boolean after promise resolved

一笑奈何 提交于 2019-12-22 04:19:09

问题


I'm trying to return a boolean after a promise resolves but typescript gives an error saying

A 'get' accessor must return a value.

my code looks like.

get tokenValid(): boolean {
    // Check if current time is past access token's expiration
    this.storage.get('expires_at').then((expiresAt) => {
      return Date.now() < expiresAt;
    }).catch((err) => { return false });
}

This code is for Ionic 3 Application and the storage is Ionic Storage instance.


回答1:


You can return a Promise that resolves to a boolean like this:

get tokenValid(): Promise<boolean> {
  // |
  // |----- Note this additional return statement. 
  // v
  return this.storage.get('expires_at')
    .then((expiresAt) => {
      return Date.now() < expiresAt;
    })
    .catch((err) => {
      return false;
    });
}

The code in your question only has two return statements: one inside the Promise's then handler and one inside its catch handler. We added a third return statement inside the tokenValid() accessor, because the accessor needs to return something too.

Here is a working example in the TypeScript playground:

class StorageManager { 

  // stub out storage for the demo
  private storage = {
    get: (prop: string): Promise<any> => { 
      return Promise.resolve(Date.now() + 86400000);
    }
  };

  get tokenValid(): Promise<boolean> {
    return this.storage.get('expires_at')
      .then((expiresAt) => {
        return Date.now() < expiresAt;
      })
      .catch((err) => {
        return false;
      });
  }
}

const manager = new StorageManager();
manager.tokenValid.then((result) => { 
  window.alert(result); // true
});



回答2:


Your function should be:

get tokenValid(): Promise<Boolean> {
    return new Promise((resolve, reject) => {
      this.storage.get('expires_at')
        .then((expiresAt) => {
          resolve(Date.now() < expiresAt);
        })
        .catch((err) => {
          reject(false);
      });
 });
}


来源:https://stackoverflow.com/questions/45663663/typescript-returning-boolean-after-promise-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!