处理获取响应的正确方法是什么 [英] What is correct way to handle fetch response

查看:19
本文介绍了处理获取响应的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于处理获取响应的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆