javascript - Cum pot să returnez doar tipul de rezolvare într-un Promise?
let companyInfo: PublicCompanyAPIResponseType;
companyInfo = await get<PublicCompanyAPIResponseType>({
url: getCompanyDataURL,
}).catch(res => {
responseStatus = res.status;
});
Când aloc variabila companyInfo acelei funcții get
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 Code afișează această eroare
Cum poate funcția mea get să returneze doar PublicCompanyAPIResponseType?
Răspuns #1
încearcă asta, dacă funcționează
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
});
Răspunsul #2
Ai încercat să adaugi pur și simplu Promise<T> în instrucțiunea de returnare?
export async function get<T>({ url, headers }: ApiConnectSet): Promise<T> {
return new Promise<T>((resolve, reject) => {
//your code
}
);
