我有以下用于处理 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);
});
});
我想添加响应状态检查,所以我是这样开始的
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 将错误文本保留在内部data.message
, but response.json()
还给我一个Promise
代替data
.
处理此案的正确方法是什么?
UPDATE
response like
你正在成为牺牲品明确的Promise创建反模式 https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it。你不需要new Promise
完全在该代码中,并且要添加状态检查,只需在then
处理程序:
return fetch(uri, { method, headers, body: JSON.stringify(data) })
.then(response => {
if (!response.ok) {
return response.json()
.catch(() => {
// Couldn't parse the JSON
throw new Error(response.status);
})
.then(({message}) => {
// Got valid JSON with error response, use it
throw new Error(message || response.status);
});
}
// Successful response, parse the JSON and return the data
return response.json();
});
Now:
- 如果返回有效 JSON 正文的错误,我们尝试使用
message
从解析的 JSON 作为错误(拒绝),回到response.status
如果没有的话。
- 如果主体返回的错误不是有效的 JSON,我们使用
response.status
作为错误(拒绝)
- 如果返回成功,我们返回解析结果
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)