I have the following code below. What i want to do is handle the network error case and the returned HTTP server error cases separately.
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(errorText) {
return failure (errorText);
})
However, unlike Promise.resolve()
, Promise.reject()
does not wait to resolve the promise from response.text()
before returning it. I have managed to receive a resolved promise by adding async/await like that:
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(async function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(await response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(errorText) {
failure(errorText);
});
Is this the only way to reach my goal?
I have also tried doing this:
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(textPromise) {
return textPromise;
}).then(function(text) {
console.log(text);
})
But the final then with the console.log
is called always, even when i call Promise.resolve()
in the code above it, as it was attached on the promise from fetch function itself. Do you know why this happens.