I am doing a simple fetch using Typescript in a Class, which should return a promise, then I want to get the JSON response from this fetch. However, no matter what change I make, the function is always returning a Promise<void | T>
which is ruining the type checking in my code.
export class ApiHelper {
constructor() { }
public FetchFromPortal<T>(xyz: string) {
------ Other less relevant code -----------
return fetch(url, options)
.then((response) => this.CheckStatus(response))
.then((response) => this.ParseJSON<T>(response))
.then((response) => {
console.log(response);
return response;
})
.catch((error: Error) => { console.log(error) });
}
private CheckStatus(response : Response) : Promise<Response> {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
} else {
let error = new Error(response.statusText);
throw error;
}
}
private ParseJSON<T>(response : Response) {
return response.json() as Promise<T>;
}
}
I'm then subsequently calling it like this:
let result = apiHelper.FetchFromPortal<T>(xyz);
According to Typescript, this is returning a Promise<void | T>
. I've tried resolving the promise in the call like so:
let result = apiHelper.FetchFromPortal<T>(xyz).then(data => { return data });
Which should in theory resolve the Promise
but this doesn't appear to be working.
Any reason why the promise isn't resolving to just the object?
console.log(response);
? – zerkmsPending Promise
state at that point. I'll update my original question. – Dandyvoid
inPromise<void | T>
comes from yourcatch
. If an error occurs, your code swallows it, effecting thevoid
. That is, if there is an error, there is no resolvedT
value. – cartant