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

use*_*015 8 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 });
}
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*tin 12

你可以返回一个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;
    });
}
Run Code Online (Sandbox Code Playgroud)

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

这是TypeScript游乐场中的一个工作示例:

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
});
Run Code Online (Sandbox Code Playgroud)


Man*_*ort 6

您的功能应为:

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