Как вернуть только тип разрешения в Обещании? - PullRequest
4 голосов
/ 12 марта 2020
let companyInfo: PublicCompanyAPIResponseType;
companyInfo = await get<PublicCompanyAPIResponseType>({
    url: getCompanyDataURL,
}).catch(res => {
    responseStatus = res.status;
});

Когда я присваиваю переменную companyInfo, получаю удовольствие c

export async function get<T>({ url, headers }: ApiConnectSet): Promise<T> {
return new Promise((resolve, reject) => {
    fetch(url, {
        method: 'GET',
        credentials: 'same-origin',
        headers: headers,
    })
        .then(async res => {
            if (res.ok) {
                return resolve((await res.json()) as Promise<T>);
            } else if (res.status === 401) {
                const redirectPath = window.location.pathname;
                window.location.href =
                    '/login?redirectPath=' + redirectPath;
            } else {
                reject(res);
            }
        })
        .catch(error => {
            reject(error);
        });
});

}

Код Visual Studio показывает эту ошибку enter image description here

Как моя функция get может только вернуть PublicCompanyAPIResponseType?

Ответы [ 2 ]

2 голосов
/ 12 марта 2020

попробуйте, если работает

let companyInfo: PublicCompanyAPIResponseType;
try {
  companyInfo = await get<PublicCompanyAPIResponseType>({
    url: getCompanyDataURL,
  })
} catch(err => {
    // get the status from error object and assign it to response status
    responseStatus = // your status code
});
0 голосов
/ 12 марта 2020

Вы пытались просто добавить Promise<T> в операторе возврата?

export async function get<T>({ url, headers }: ApiConnectSet): Promise<T> {
    return new Promise<T>((resolve, reject) => {
        //your code
    }
);
...