gpt4 book ai didi

javascript - promise 解决后 typescript 返回 bool 值

转载 作者:数据小太阳 更新时间:2023-10-29 04:27:28 33 4
gpt4 key购买 nike

我试图在 promise 解决后返回一个 bool 值,但 typescript 给出了一个错误说

“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 实例。

最佳答案

您可以返回解析为 bool 值的 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;
});
}

您问题中的代码只有两个返回语句:一个在 Promise 的 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
});

关于javascript - promise 解决后 typescript 返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663663/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com