Answer the question
In order to leave comments, you need to log in
Why does reject return unknown?
Hello. Please tell me, I'm trying to wrap fetch with a function, for more convenient work with json:
interface ResponseData{
status: boolean;
data?: object;
}
function sendQuery(url: string, data: object): Promise<ResponseData>
{
return fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then((response: Response) => {
return response.json();
}).then((data) => {
return new Promise((resolve, reject) => {
resolve({
status: true,
data: data
});
});
}).catch(() => {
return new Promise((resolve, reject) => {
reject({
status: false
});
});
});
}
Type 'Promise<unknown>' is not assignable to type 'Promise<ResponseData>'.
Answer the question
In order to leave comments, you need to log in
This happens because your function is not properly organized: you claim that sendQuery will return a promise, but in fact you return a promise (return fetch), which will return a promise in which ResponseData. If you want to return a promise, then you either 1) return the original one returned to you by fetch and the rest of the methods in the chain, or 2) return the one you created, like in the asynchronous delay example:
function delay(duration: number): Promise<any> {
return new Promise(res => setTimeout(res, duration))
}
Turned over too much.
Firstly: there are helpers Promise.reslove(data)
and Promise.reject(error)
, and secondly: when returning from then
\ catch
, even they are not needed.
interface ResponseData {
status: boolean;
data?: object;
}
function sendQuery(url: string, data: object): Promise<ResponseData> {
return fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response =>
response.json()
).then(data => ({
status: true,
data: data
})).catch(() => {
throw {
status: false
}
});
}
new Promise
Promise<unknown>
new Promise
new Promise<Type>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question