簡體   English   中英

提取泛型並返回元組泛型

[英]Extract generic type and return tuple generic type

我有這個 function,它采用Promise<T>並且當前返回Promise<(null | any)[] | (any | null)[]> Promise<(null | any)[] | (any | null)[]> ,
我希望它返回Promise<[Error, T]>

                                          //↓Here I want to pass the extracted type
const customAsyncAwait = <T extends Promise<any>>(promise: T) => {

  return (promise)
    .then(res => [null, res])
    .catch(error => [error, null]);

}

我是這樣用的

async function init() {

  const api = axios.get<Plants[]>('<API_NAME>'); //typeof api =  Promise<AxiosResponse<Plants[], any>>
  const [error, data] = await customAsyncAwait(api); //Currently, typeof data = any but I want it to be AxiosResponse<Plants[], any>

}

更新

我設法讓它工作,但看起來很丑,有沒有更好的方法?

const customAsyncAwait = <T>(promise: Promise<T>): Promise<[Error, T]> => {
  const result: [Error, T] = [null, null];

  return promise
    .then((res) => {
      result[0] = null;
      result[1] = res;
      return result;
    })
    .catch((error: Error) => {
      result[0] = error;
      result[1] = null;
      return result;
    });
}

從這個 package await-to-js找到解決方案

const customAsyncAwait = <T>(promise: Promise<T>): Promise<[Error, T]> => {
  return promise
    .then<[null, T]>((res: T) => {
      return [null, res];
    })
    .catch<[Error, null]>((error: Error) => {
      return [error, null];
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM