Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

chaining - 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)

question from:https://stackoverflow.com/questions/65886935/how-to-avoid-redundancy-when-chainig-functions-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...