2017-08-13 60 views
3

我想要一个承诺解析后返回一个布尔值,但打字稿给出了一个错误说承诺后打字稿返回布尔解决

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

你不能做到这一点...您可以通过只返回返回'无极'' this.storage.get ...'虽然。 – Gerrit0

+0

@ user2473015我通常没有在get中看到异步代码,而是异步进程设置了一个属性,get得到了... – JGFMK

+1

而且你可能不应该为有副作用的东西使用getter。 – Bergi

回答

3

可以返回一个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语句:一个无极的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 
}); 
+0

向问题添加了其他信息。 – user2473015

+0

@ user2473015恐怕我不知道在这个答案中提供了哪些附加信息。 –

1

你的功能应该是:

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