承诺解决后打字稿返回布尔值
Typescript returning boolean after promise resolved
我试图在承诺解决后 return 一个布尔值,但打字稿给出了一个错误说
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 应用程序,存储是 Ionic Storage 实例。
您可以 return 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 语句:一个在 Promise 的 then
处理程序中,一个在其 catch
处理程序中。我们在 tokenValid()
访问器中添加了第三个 return 语句,因为访问器也需要 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
});
你的函数应该是:
get tokenValid(): Promise<Boolean> {
return new Promise((resolve, reject) => {
this.storage.get('expires_at')
.then((expiresAt) => {
resolve(Date.now() < expiresAt);
})
.catch((err) => {
reject(false);
});
});
}
我试图在承诺解决后 return 一个布尔值,但打字稿给出了一个错误说
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 应用程序,存储是 Ionic Storage 实例。
您可以 return 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 语句:一个在 Promise 的 then
处理程序中,一个在其 catch
处理程序中。我们在 tokenValid()
访问器中添加了第三个 return 语句,因为访问器也需要 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
});
你的函数应该是:
get tokenValid(): Promise<Boolean> {
return new Promise((resolve, reject) => {
this.storage.get('expires_at')
.then((expiresAt) => {
resolve(Date.now() < expiresAt);
})
.catch((err) => {
reject(false);
});
});
}