【发布时间】:2021-09-16 12:53:49
【问题描述】:
我有一个异步等待处理程序:
const asyncHandler = async <Type>(
promise: Promise<Type>
): Promise<[Type, null] | [null, string]> => {
try {
const response = await promise
return [response, null]
} catch (error) {
console.log(error)
return [null, error]
}
}
export default asyncHandler
这不会给我任何错误:
import asyncHandler from './async_handler'
interface Success {
payload: string
}
interface MyError {
payload: undefined
error?: true
}
const fetchData = async (): Promise<Success | MyError> => {
const fetchDataResponse = await asyncHandler<string>(
new Promise((resolve) => {
setTimeout(() => resolve('potato'), 200)
})
)
if (fetchDataResponse[1]) return { payload: undefined, error: true }
return { payload: fetchDataResponse[0] }
}
export default fetchData
但这会给出类型错误,因为期望响应是字符串或未定义但响应是字符串或空
import asyncHandler from './async_handler'
interface Success {
payload: string
}
interface MyError {
payload: undefined
error?: true
}
const fetchData = async (): Promise<Success | MyError> => {
const [response, error] = await asyncHandler<string>(
new Promise((resolve) => {
setTimeout(() => resolve('potato'), 200)
})
)
if (error) return { payload: undefined, error: true }
return { payload: response } // Type 'string | null' is not assignable to type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'.ts(2322)
}
export default fetchData
我知道响应不仅设置为字符串类型,因为这两个变量现在是独立的,但是有没有办法让第二个示例像第一个示例一样工作?
【问题讨论】:
-
只是一个建议 - 您应该在
catch块中使用console.error()而不是console.log() -
哇,谢谢。我会用! :D
标签: javascript typescript async-await promise