Wait for the function to finish when it is called from the loop that diff. settings


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?

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

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.