诺言解决后,Typescript返回布尔值

时间:2017-08-13 18:36:45

标签: javascript typescript es6-promise ionic3 ionic-storage

我试图在promise解析后返回一个布尔值,但是typescript会给出错误说

A 'get' accessor must return a value.

我的代码看起来像。

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 });
}

此代码适用于Ionic 3 Application,存储是Ionic Storage实例。

2 个答案:

答案 0 :(得分:10)

你可以返回一个解析为布尔值的Promise,如下所示:

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;
    });
}

你问题中的代码只有两个return语句:一个在Promise的then处理程序中,另一个在catch处理程序中。我们在tokenValid()访问器中添加了第三个return语句,因为访问者也需要返回一些东西。

以下是一个工作示例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
});

答案 1 :(得分:5)

你的功能应该是:

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