0

I want the sequence of execution to be as follows. 1. unattach(x) 2. updateLists(y) 3. console.log("completed execution of function update")

Only after both the functions (unattach & updateLists) have completed execution then the update function should return. The problem is I am not able to make it wait for both functions to complete execution. Is there something wrong in the return statement ?

    function main()
    {
        when(update).then(function(){
        console.log("completed execution of function update");
        });
    }

    function update()
    {
    return when(function(){
            unattach(x);
            }).then(function(){
                    updateLists(y);
                    }); 
    }
Priyanka A
  • 63
  • 1
  • 1
  • 6

1 Answers1

1

I'd rewrite it like this, using callbacks. Anyway, you should write more code.

function main() {

    update(function(){
       console.log("completed execution of function update");
    });

}

function update(callback){
        unattach(x, function(){
           updateLists(y, function(){
              if(callback){
                 callback();
              }
            });
        }); 
}

Assuming there are two AJAX calls in the functions unattach and updateLists, you could do so:

function unattach(x, callback){
   // if JQuery

   $.ajax({
      ....
      success: function(){
         if(callback){
           callback();
         }
      }
   });
}

In the same way you should define updateLists, so the callback function gets called when AJAX has finished its job.

Giancarlo PSK
  • 231
  • 1
  • 7
  • This will change the update function. I am using the update function in multiple locations in my code. I dont want to call console.log code from within update. – Priyanka A May 21 '14 at 21:00
  • Sorry, but the fragment of code provided does not suffice to see exactly ehat's going on in your program. Why do you need to return something in the update function? And why does it differ when applied in other parts of code. It should behave the same way. Also, if not in the scope, you should add x and y as parameters. – Giancarlo PSK May 21 '14 at 21:04
  • There are http get and post requests in unattach & updateLists. It needs to follow a sequence for execution. Only when those requests have completed, I want to go back to the main function and perform some operations. I am not returning any value from the update function, I want the flow to return only after successful completion of update function and all the functions within the update function. – Priyanka A May 21 '14 at 21:16
  • Are you using JQuery? I updated the answer with how you should add callbacks to use them in AJAX functions. Hope it's clear! – Giancarlo PSK May 21 '14 at 21:24