Search code examples
javascriptchainingredundancy

How to avoid redundancy when chainig functions in javascript?


I created a function which handles update's for me and you can choose between post and get updates.

The only thing in which post/get differ is the start call (axios.post()/axios.get()).

Afterwards they get the same functions chained (.then(), .catch())

Nevertheless, I don't see another way than writing an if/else statement and writing the chained functions twice, which leads to mouch code and breaking DRY. How can I avoid this?

Here's my code:

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


(I don't want to export my code to functions)


Solution

  • Well, you have 2 ways to do that:

    The first one is using your way, with callbacks. You just need to store the request in a variable, and then use the "then/catch" on this one.

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

    The 2nd way, a better way in my opinion, is to simply make your function async and return the request (which is a promise). Using this way, you can easily manage async stuff using promises.

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