javascript - 将 switch case 重构为它自己的类方法。如何?

标签 javascript

我有一个用于获取 promise 的包装器类,我想控制 http 响应状态。

目前开关在 get() 方法中。如何将这个 switch case 转移到 error() 方法中并将其用作“thenable”?

看看:

class CustomFetch {


  get(url) {

    return new Promise((resolve, reject) => {

      const getOptions = {
        method: 'GET',               // *GET, POST, PUT, DELETE, etc.
        mode: 'cors',                // no-cors, cors, *same-origin
        cache: 'no-cache',           // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin',  // include, *same-origin, omit
        headers: {
          // 'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Type': 'application/json',
          // 'Content-Type': 'text/xml'
        },
        redirect: 'follow',          // manual, *follow, error
        referrer: 'no-referrer',     // no-referrer, *client
        // body:     JSON.stringify(params)   // body data type must match "Content-Type" header
      };

      // DO FETCH
      fetch(url, getOptions)

      .then(function(res) {

        // RESPONSE VALIDATION
        switch (res.status) {

          case 200:
            // code...
            console.info('HTTP GET response status:', res.status, 'OK');
            break;

          case 201:
            // code...
            console.info('HTTP GET response status:', res.status, 'Created');
            break;

          case 404:
            // code...
            throw new Error('HTTP GET response status: 404 Not Found.');
            break;

          case 500:
            // code...
            throw new Error('HTTP GET response status: 500 Internal Server Error.');
            break;

          case 503:
            // code...
            throw new Error('HTTP GET response status: 503 Service Unavailable.');
            break;
          
          default:
            // code...
            break;

          }

          return res;

        })

        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err));


    });

  }
  
  error(res) {
  
  // Here, for example..
  
  }
  
}

const http = new CustomFetch;

async function Run() {


// GET -> AWAIT...
const fetch1 = await http.get('https://jsonplaceholder.typicode.com/users/1')
.then(data => console.log(data))
.then(data => console.log('asycn/await: Resource Get Successful.'))
.then(data => console.log('_'))
.catch(err => console.log(err));

}

// RUN async /await fetch functions in procedural order.
Run();

最佳答案

如果我正确理解您的问题,您想将 switch 语句移出到类的错误方法中吗?

因为它在 promise 链中,所以错误方法需要返回一个 promise 。

也许像下面这样的东西会起作用:

error(res) {
  switch (res.status) {
    case 200:
      // code...
      console.info('HTTP GET response status:', res.status, 'OK');
      break;
    case 201:
      // code...
      console.info('HTTP GET response status:', res.status, 'Created');
      break;
    case 404:
      // code...
      throw new Error('HTTP GET response status: 404 Not Found.');
      break;
    case 500:
      // code...
      throw new Error('HTTP GET response status: 500 Internal Server Error.');
      break;
    case 503:
      // code...
      throw new Error('HTTP GET response status: 503 Service Unavailable.');
      break;
    default:
      // code...
      break;
    }
    return res.json();
}

您还需要删除此语句:

.then(res => res.json())

调用之后。

所以您的 get 方法现在看起来像:

(编辑:正如已经指出的那样,我们必须尽量避免 explicit constructor antipattern ,因此我们将返回整个 promise 并将解决和拒绝推迟到调用者)

// code above the fetch...
return fetch(url, options)
  .then(this.error);

关于javascript - 将 switch case 重构为它自己的类方法。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700640/

相关文章:

javascript - 如何修复阻止下拉列表工作的 JavaScript 函数

javascript - 为什么直接在对象文字上访问属性会抛出 SyntaxError?

javascript - jQuery Mobile 1.2.0 任何页面 onClick 隐藏固定页脚

javascript - 试图删除子元素的最后一个子元素

c# - 根据链接点击隐藏jquery中的gridview

javascript - 无需重新加载页面且无需使用 Ajax 即可刷新 Div、Table 或 TR

javascript - 在 OpenLayers 3 中检测点击多边形的顶点或边缘?

javascript - 像矩阵一样访问 javaScript 对象数组

javascript - 响应式 jQuery 不起作用 : Click below 768px width and hover above 768px

javascript - 从 JSON 数组中删除字段