【发布时间】:2021-02-11 19:41:20
【问题描述】:
我有一个箭头函数,它比较两个值。 一个值来自另一个函数,该函数从 API 端点获取值。 我想使用 await / async 样式而不是 Promises(.then、.catch、.finaly)。
在 JavaScript 中这很容易,但我在使用 TypeScript 时遇到了一些问题。如何正确编写该函数?
我有这样的东西(伪代码):
compareValues: Promise<boolean> = async () => {
try {
const value1 = false;
const value2 = this.getValue2;
const isEqual = (await value2) === value1;
return isEqual;
} catch (error) {
throw error;
}
}
getValue2 = async () => {
try {
const value2 = await axios.get(url, config);
const value2Data = await value2.data;
return value2Data;
} catch (error) {
throw error;
}
export interface IInterface {
compareValues: () => Promise<boolean>;
}
const initialState: IInterface = {
compareValues: () => {
return Promise.resolve(false);
}
}
使用该代码,IDE 会要求第一行:Type '() => Promise' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag] 虽然编译器告诉:Type 'Promise' 不能分配给 type '() => Promise'。 类型“Promise”不匹配签名“(): Promise”。 TS2322
我感觉我的返回类型是错误的......
代码会将我的 isEqual 值包装在 Promise 中吗?
我可以避免这两个函数都是异步的吗?
什么是正确的语法?
提前谢谢你!
【问题讨论】:
-
compareValues: Promise<boolean>应该是compareValues: () => Promise<boolean>- 毕竟compareValues拥有一个函数,它会在被调用时产生一个promise。现在还不是真正的承诺。如果您需要 Promise 本身,则需要调用该函数。 -
谢谢!这就是问题所在!我刚刚将
compareValues: Promise<boolean> = async () => {更改为compareValues = async () => {并且它正在工作。
标签: reactjs typescript asynchronous async-await