在javascript中使用chainig函数时如何避免冗余?

问题描述

我创建了一个为我处理更新的函数,您可以在发布和获取更新之间进行选择。

post/get 唯一不同的是开始调用 (axios.post()/axios.get())。

之后,它们将相同的函数链接起来 (.then(),.catch())

尽管如此,除了编写 if/else 语句和编写链接函数两次之外,我没有看到其他方法,这会导致大量代码和破坏 DRY。 我怎样才能避免这种情况?

这是我的代码

update function(
      url,usepost = true,arg = {},callback = () => {},errorcb = () => {}
    ) {
      console.log(arg);
      if (usepost) {
        axios
          .post("https://example.com/" + url,arg)
          .then(response => {
            //do stuff
            callback();
          })
          .catch(error => {
           // do error stuff
            errorcb();
          });
      } else {
        axios
          .get("example.com/" + url,{ params: arg })
          .then(response => {
           // do stuff

            callback();
          })
          .catch(error => {
            // do error stuff
            errorcb();
          });
      }
    }


(我不想将代码导出到函数

解决方法

好吧,您有两种方法可以做到这一点:

第一个是使用您的方式,带有回调。您只需要将请求存储在一个变量中,然后在这个变量上使用“then/catch”。

function update(
    url,usepost = true,arg = {},callback = () => {},errorcb = () => {}
) {
    let request;
    if (usepost) {
      request = axios.post("https://example.com/" + url,arg)
    } else {
      request = axios.get("example.com/" + url,{ params: arg })
    }
    request.then(response => {
    // do stuff

        callback();
    })
    .catch(error => {
        // do error stuff
        errorcb();
    });
}

第二种方法,在我看来更好的方法是简单地使您的函数异步并返回请求(这是一个承诺)。通过这种方式,您可以使用 Promise 轻松管理异步内容。

async function update(
    url,arg = {}
) {
    if (usepost) {
      return axios.post("https://example.com/" + url,arg)
    } else {
      return axios.get("example.com/" + url,{ params: arg })
    }
}