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
message
from the parsed JSON as the error (rejection), falling back onresponse.status
if there isn't one. - If an error is returned by the body isn't valid JSON, we use
response.status
as the error (rejection) - If a success is returned, we return the result of parsing it
这篇关于处理获取响应的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理获取响应的正确方法是什么


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01