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

What is correct way to handle fetch response

我有以下代码用于处理 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);
        });
    });

而且我想添加响应状态检查,所以我就这样开始了

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() return 我 Promise 而不是 data

处理这种情况的正确方法是什么?

更新 回应喜欢

您正在成为 explicit Promise creation antipattern 的牺牲品。您根本不需要该代码中的 new Promise,要添加状态检查,只需在 then 处理程序中执行即可:

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();
    });

现在:

  • 如果错误是 returned with valid JSON body,我们尝试使用解析的 JSON 中的 message 作为错误(拒绝),回退在 response.status 如果没有。
  • 如果正文 return 错误 JSON,我们使用 response.status 作为错误(拒绝)
  • 如果 return 成功,我们 return 解析它的结果

第二个就可以了然后你可以用Promise.all代替

fetch(uri, { method, headers, body: JSON.stringify(data) })
        .then(response => {
          return Promise.all([response.json(),response])
        })
        .then(([responseData,response]) => {
          // handle data here
        })

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all