诺言解决后,Typescript返回布尔值 [英] Typescript returning boolean after promise resolved

查看:272
本文介绍了诺言解决后,Typescript返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

'get'访问者必须返回一个价值。

我的代码看起来像。

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应用程序,存储是Ionic Storage实例。

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

推荐答案

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

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

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

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

这篇关于诺言解决后,Typescript返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆