Javascript 承诺解决后打字稿返回布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45663663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript returning boolean after promise resolved
提问by user2473015
I'm trying to return a boolean after a promise resolves but typescript gives an error saying
我试图在承诺解决后返回一个布尔值,但打字稿给出了一个错误说
A 'get' accessor must return a value.
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.
此代码用于 Ionic 3 应用程序,存储为 Ionic Storage 实例。
回答by Shaun Luttin
You can return a Promisethat resolves to a boolean like this:
您可以返回Promise解析为布尔值的a ,如下所示:
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 thenhandler and one inside its catchhandler. We added a third return statement inside the tokenValid()accessor, because the accessor needs to return something too.
您问题中的代码只有两个 return 语句:一个在 Promise 的then处理程序中,一个在其catch处理程序中。我们在访问器中添加了第三个 return 语句tokenValid(),因为访问器也需要返回一些东西。
Here is a working example in the TypeScript playground:
这是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
});
回答by Mankeomorakort
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);
});
});
}

