Serial invocation of JS functions

Wednesday, July 2, 2014

Here is what I am trying to do (The actual problem is different, but an overview of it is as follows):

  1. I have an array [A..Z].

  2. For each alphabet from the above array, I have another array as:

    someArray[alphabet] = [1..100] //another array

  3. For each number in someArray[alphabet], there is yet another array:

    anotherArray[number] = [a..z,A..Z,1..1000]

Assume that for each alphabet, I fetch someArray[alphabet], and for each number in someArray[alphabet], I fetch anotherArray[number], all from the server - It takes time.

Also, the functions to get them are as follows - I make jQuery post calls to get data from the server. I need to execute them in order.

//I get them here
//For Each alpha, I call:
//I get someArray here.
//For Each element in someArray
//I get them here
//For Each element in anotherArray
//get all [a..z,A..Z,1..1000]
//display them

The problem is an iteration of getNumbers(alpha) does not wait for the getAnotherArray(previousIteration) to complete. The executions (function invocations run in parallel (simultaneous executions for A..Z) and not otherwise.

My steps:

  1. I am able to retrieve all data as expected, but not sequentially.

  2. I tried using flags and setInterval, clearInterval to allow/disallow next iterations - They do not work as expected.

  3. I also tried using something like - getAlphabets() && getNumbers() & getAnotherArray(), thinking that that would execute sequentially, but I was wrong.