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

Dmi*_*nko 2 javascript fetch promise

我有以下代码用于处理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);
        });
    });
Run Code Online (Sandbox Code Playgroud)

我想添加响应状态检查,所以我已经开始像这样

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);
        });
    });
Run Code Online (Sandbox Code Playgroud)

Magento将错误文本保留在其中data.message,但response.json()返回a Promise而不是data

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

UPDATE响应像 在此处输入图片说明

T.J*_*der 8

您将成为显式Promise创建反模式的牺牲品。您根本不需要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();
    });
Run Code Online (Sandbox Code Playgroud)

现在:

  • 如果使用有效的JSON正文返回了错误,则我们尝试message从解析的JSON中使用该错误作为错误(拒绝),response.status如果没有错误,请重新使用。
  • 如果正文返回的错误不是有效的JSON,我们将其response.status用作错误(拒绝)
  • 如果返回成功,则返回解析结果