I'm having trouble understanding Promise.resolve.
I'm writing a very simple wrapper for fetch to avoid having to write a then
just to access the JSON. I found a code snippet online that looked a bit like this:
function get(url) {
return fetch("/api/" + url, {
method: "GET",
credentials: 'include'
}).then(response => {
if (response.ok) {
return response.json().then(json => {
return Promise.resolve({ data: json, response: response });
}).catch(err => {
return Promise.resolve({ response: response });
});
} else {
return response.json().catch(err => {
throw new Error(response.statusText);
}).then(json => {
throw new Error(json.error.message);
});
}
});
}
However, it doesn't seem like you need the Promise.resolve
function calls. I tried removing them and just writing return { data: json, response: response };
instead and it still works.
Are the resolve
calls doing anything? Are they necessary?