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

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

问题描述

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

更新 像这样的回应

UPDATE response like

推荐答案

您正在成为

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天全站免登陆