skip to Main Content

I have a couple of JavaScript functions that call ajax promises to populate fields. Like this:

var functionA = function () {
   //Prepare data for ajax service call
   service.getDataA()
      .then((data) => $("#inputA").val(data));
}
var functionB = function () {
   //Prepare data for ajax service call
   service.getDataB()
      .then((data) => $("#inputB").val(data));
}

Here are the ajax

var getDataA  = function () {
    return $.ajax({
        type: "GET",
        url: url,
        data: data,
    });
};

var getDataB  = function () {
    return $.ajax({
        type: "GET",
        url: `url,
        data: data,
    });
};

So far, so good.

The issue is, I have a third function, functionC, that depends on the completion of functionA and functionB. I need functionC to execute when both functionA and functionB are complete. I have tried several ways to try to achieve this, with no success.

How do I accomplish something like this?

When functionA and functionB are done
.Then functionC. 

3

Answers


  1. As Daniel has said in the comments. Promise.all is the best solution. If you cannot use it for some reason, a pattern that could work is the following:

    // some globally-accessible state
    const returnStates = {
      hasA: false,
      hasB: false,
      hasC: false,
    };
    
    const tryC = () => {
      if (!returnStates.hasA || !returnStates.hasB) return
    
      service.getDataC();
    
      returnStates.hasC = true;
    };
    
    getDataA.then(() => {
      returnStates.hasA = true;
    
      tryC();
    });
    
    getDataB.then(() => {
      returnStates.hasB = true;
    
      tryC();
    });
    

    You can adapt this to contain returnStates differently, wrap it in tryC, or use a global state management tool. This mimics redux-thunk essentially without the redux or the thunk.

    Login or Signup to reply.
  2. You could use Promise.all, example:

    var functionA = function () {
       return service.getDataA()
          .then((data) => $("#inputA").val(data));
    }
    
    var functionB = function () {
       return service.getDataB()
          .then((data) => $("#inputB").val(data));
    }
    
    var functionC = function () {
        // functionC logic here
    }
    
    Promise.all([functionA(), functionB()])
        .then(functionC)
        .catch((err) => {
            // Handle error
            console.error(err);
        });
    
    Login or Signup to reply.
  3. Promise.all() is the guy, something like this:

    var promise1 = new Promise(function (resolve, reject) {
      //your Function1
    });
    
    var promise2 = new Promise(function (resolve, reject) {
      //your Function2
    });
    
    
    Promise.all([promise1, promise2])
       .then(res => {
        //your Function3
    })
    .catch(error => console.log(error))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search