I am a bit confused with how to properly use fetch. It seems to resolve even when I get an error status back. Is the below code correct (wrapping the fetch in another promise)?
function a(url, config) {
if (!config)
config = {};
config = Object.assign(config, {
headers: {
'content-type': 'application/json;charset=utf-8'
}
})
return new Promise(
function(resolve, reject) {
fetch(url, config).then(
function(res) {
if (res.status == 200 && res.ok) {
console.log("Promise resolved")
resolve(res);
return;
}
console.log("Promise rejected")
reject(res);
},
function(rej) {
console.log("promise rejected")
reject(rej);
}
)
}
)
}
function b() {
a('/test').then(
function(res) {
console.log('success');
console.log(res)
},
function(rej) {
console.log('Rejected');
console.log(rej)
}
)
}
b();
fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected.
The only thing to understand is that once resolved (or rejected), that is it for a defered object - it is done. If you call then(...) on its promise again, you immediately get the (first) resolved/rejected result. Additional calls to resolve() will not have any effect.
If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then.
If you want to reject from success callback you need to do it explicitly by either returning rejected promise, e.g. return Promise.reject('error occurred');
or by throwing.
Additionally, you should not abuse Promise
constructor in your case since fetch
already returns promise object:
function a(url, config) {
if (!config)
config = {};
config = Object.assign(config, {
headers: {
'content-type': 'application/json;charset=utf-8'
}
});
return fetch(url, config).then(
function(res) {
if (res.status == 200 && res.ok) {
console.log("Promise resolved")
return res.json();
}
console.log("Promise rejected");
throw 'promise rejected';
},
function(rej) {
console.log("promise rejected");
throw 'promise rejected';
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With