What is correct way to handle fetch response(处理获取响应的正确方法是什么)
问题描述
我有以下用于处理 Magento 2 REST API 的代码.
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 将错误文本保存在 data.message 中,但 response.json() 会返回一个 Promise 而不是 data代码>.
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?
更新像这样的回应
推荐答案
你正在成为 显式 Promise 创建反模式.您根本不需要该代码中的 new Promise,要添加状态检查,只需在 then 处理程序中进行:
You're falling prey to the explicit Promise creation antipattern. You don't need new Promise in that code at all, and to add the status check, simply do it in a then handler:
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();
});
现在:
- 如果返回带有有效 JSON 正文的错误,我们会尝试使用解析后的 JSON 中的
message作为错误(拒绝),如果返回则返回response.status没有. - 如果正文返回的错误不是有效的 JSON,我们使用
response.status作为错误(拒绝) - 如果返回成功,则返回解析结果
- If an error is returned with valid JSON body, we try to use
messagefrom the parsed JSON as the error (rejection), falling back onresponse.statusif there isn't one. - If an error is returned by the body isn't valid JSON, we use
response.statusas the error (rejection) - If a success is returned, we return the result of parsing it
这篇关于处理获取响应的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理获取响应的正确方法是什么
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
