Question

I am calling one function from another function

  • The first function(from which the call to the other function is made) contains a loop which passes different parameter values to the second function
  • The second function contains a PageMethod call which includes an OnSuccess and an OnFailure function ...

How can I make the script wait for the completion of the first call to the second function and then execute next call?

Is there any Javascript that wait for functions to finish execution?

Something that synchronizes function calls?

Was it helpful?

Solution

Synchronizing asynchronous function calls can be done by either using promises, providing callbacks or by queueing up the function calls.

Promises are easy to handle, makes your code readable and is pretty much the recommended way to go when dealing with asynchronous calls. With promises you would do well to use one of the libraries available, i.e. Q, when.js or if you're more familiar with jQuery you can use jQuery.Deferred().

With callbacks you let your asynchronous function take a function parameter that it executes after it's primary logic ha been executed. E.g

function (param, callbackFn) {
   // primary asynchronous logic
   callbackFn();
}  

The downside with callbacks is that it can be quite hard to follow the program flow. And it's easy to fall into "function nesting hell".

Using a queue might be a suitable alternative to the other options. Here's an example queue

var queue = function(funcs, scope) {
    (function next() {
        if(funcs.length > 0) {
            funcs.shift().apply(scope || {}, [next].concat(Array.prototype.slice.call(arguments, 0)));
        }
    })();
};

This would be used accordingly

queue([asyncFn1, asyncFn2, asyncFn3]);

See this tutorial for a detailed explanation of the queue function.

OTHER TIPS

It sounds like you're dealing with an Asynchronous sequence, may want to have a look at the async library, it can be run on client side or server side and solves exactly this kind of thing I believe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top