【发布时间】:2021-08-07 02:09:11
【问题描述】:
为什么我不能通过链接 then & catch 来返回承诺,我看不出这里有什么区别。
type SuccessResponse<T> = [T, null]
type ErrorResponse<U> = [null, U]
type Result<T, U> = Promise<SuccessResponse<T> | ErrorResponse<U>>
export const promiseWrapper = async <T, U extends Error>(
promise: Promise<T>
): Result<T, U> => {
// --- This works ---
try {
const data = await promise
return Promise.resolve([data, null])
} catch (error) {
return Promise.resolve([null, error])
}
// ---
// --- Doing this instead cause TypeScript error ---
// return promise
// .then((data) => [data, null])
// .catch((error) => Promise.resolve([null, error]))
// ---
}
这是我得到的错误。我把它读作我返回的承诺,在某种程度上不考虑“then & catch”链。通过 async/await (工作方式)和解耦承诺,编译器明白我想要返回 Result 承诺?
如果我想使用 Promise 链,我如何告诉 typescript 我的 Promise 将返回 Result?
Type '(T | null)[] | [null, any]' is not assignable to type 'SuccessResponse<T> | ErrorResponse<U>'.
Type '(T | null)[]' is not assignable to type 'SuccessResponse<T> | ErrorResponse<U>'.
Type '(T | null)[]' is not assignable to type 'ErrorResponse<U>'.
Target requires 2 element(s) but source may have fewer.
【问题讨论】:
-
有点旁注,但您的结果似乎很奇怪。您似乎采用了成功/错误回调样式并将其作为元组结果放入承诺中。而我希望错误是拒绝承诺。如果你真的想要两者,似乎你在追求
Either,这确实更有意义,但我不确定承诺中的元组是实现它的最佳方式。
标签: typescript promise compiler-errors