1

In my work, I frequently encounter following situation:

Situation A:

I need to make multiple ajax calls in one function to retrieve data from server. So I have to make callback functions and define a counter to determine whether all the calls get done.

For example , in each of the sub-functions ( with ajax calls), at the end of the done, I would callback to check the counter's value.

 ajax.done(funciton(jsResponse){  

  .......
  base.ajaxLoaded++;
  base.dataLoaded();

});

then in base function, I check the value:

 dataLoaded: function()
 {
    var _this = this;
    if (_this.ajaxLoaded == 4) 
    {
       // all loaded
       _self.render();
       _this.afterInit();
     }

   }

Situation B:

There is a modal pop up triggered by the completion of an animation. So, I have following choices:

1) make a setTimeout function with a timer ( estimated the length of animation)

something like:

setTimeout(function(){

       window.MYAPP.triggerMymodal();

},1000);

2) set up a interval function to check repeatedly whether a flag's value has changed and I embedded this flag into the animation finish function, to set it true or false. if this flag true then make my next move and kills this interval.

3) change animation div attributes and check it use interval function.

Situation C:

Use window.print() function to print something and then need detect when it's finish. This has been asked by myself in this: how to detect window.print() finish

My Question:

In JavaScript, is there a certain kind of method or Technic to deal with those functions which have unknown execution time? or this is just a case by case thing based on what technology you use?

Community
  • 1
  • 1
JavaScripter
  • 4,282
  • 9
  • 37
  • 45
  • Situation B should offer a callback as well. How are you doing the animation? – Bergi Mar 07 '14 at 04:12
  • 2
    *"is there a certain kind of method or Technic to deal with those functions which have unknown execution time"* Yep: Callbacks. You pass a function to another function and that function executes your callback whenever it is done processing. – Felix Kling Mar 07 '14 at 04:22

1 Answers1

0

Yes, the modern approach to dealing with this is called Promises. Various libraries implement the concept, which is basically that you can chain together groups of things that need to happen, either is parallel or serial, and then define success and failure outcomes for each of them. It takes a bit of time to get your head around it but once you do the code is much more straightforward.

Damon Smith
  • 1,770
  • 18
  • 24