处理获取响应的正确方法是什么

编程入门 行业动态 更新时间:2024-10-20 00:27:10
本文介绍了处理获取响应的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下用于处理 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 on response.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

更多推荐

处理获取响应的正确方法是什么

本文发布于:2023-11-26 13:15:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!