How to avoid redundancy when chainig functions in javascript? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to avoid redundancy when chainig functions in javascript? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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)

Answer

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 })
    }
}
We are here to answer your question about How to avoid redundancy when chainig functions in javascript? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji