I have following code which I using for handling Magento 2 REST API.
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return response.json();
})
.then(responseData => {
resolve(responseData);
})
.catch(error => {
reject(error);
});
});
And I want to add response status checking, so I’ve started like this
return new Promise((resolve, reject) => {
fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
return {
data: response.json(),
ok: response.ok,
status: response.statusText
};
})
.then(responseResult => {
if (responseResult.ok) {
resolve(responseResult.data);
} else {
const error = responseResult.status || responseResult.data.message;
reject(error);
}
})
.catch(error => {
reject(error);
});
});
Magento keeps error text inside data.message
, but response.json()
return me a Promise
instead of data
.
What is a correct way to handle this case?
2
Answers
You’re falling prey to the explicit
Promise
creation antipattern. You don’t neednew Promise
in that code at all, and to add the status check, simply do it in athen
handler:Now:
message
from the parsed JSON as the error (rejection), falling back onresponse.status
if there isn’t one.response.status
as the error (rejection)to get ok on the second then you can use Promise.all instead
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all