Typescript returning boolean after promise resolved(承诺解决后打字稿返回布尔值)
问题描述
我试图在承诺解决后返回一个布尔值,但打字稿给出错误提示
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;
});
}
您问题中的代码只有两个返回语句:一个在 Promise 的 then
处理程序中,一个在其 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.
这是一个工作示例 在 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
});
这篇关于承诺解决后打字稿返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:承诺解决后打字稿返回布尔值


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01