4
votes
\$\begingroup\$

I have a piece code similar to below:

But I keep having this nagging feeling that there has to be an easier way! Any ideas?

var synch = false
var indexArray = new Array();
var rowCount = theTable.find('tr').length;
$(".views").each(function(index) {
    indexArray.push( $(this).val()); // Not the real code but something to this effect
    if (rowCount <= (index+1)) synch = true;
});
while (!synch);
DO something with indexArray.....
\$\endgroup\$
3
votes
\$\begingroup\$

There is absolutely no need for the synch part - JavaScript is synchronous, and you should not get into a situation where the processing of that function (the one you're showing) will not be completed before the next line runs.

(By the way, that function you have there can be rewritten for greater efficiency)

var indexArray = $('.views').map(function(){
    return this.value;
}).get();

Let's assume that you are doing something async in that each loop, for instance, ajax calls. Your best bet is to keep a count of how many of the calls are completed in the callback function, then execute the rest of your code when the last callback function is called:

var views = $('.views'), 
    completed = 0,
    total = views.length;

views.each(function(){
    someAsyncFunction (function(){
        // Process data
        if(++completed === total) {
            // We're done! Let's move on..
        }
    });
});

This can be abstracted away into another function, though doing that is left as an exercise for the reader.

\$\endgroup\$
  • \$\begingroup\$ Thanks for that response, I am definitely doing an async call. I just thought that there may be an more elegant solution. \$\endgroup\$ – Sydwell Feb 5 '11 at 9:43
  • \$\begingroup\$ @Sydwell If you're talking about ajax specifically, you can look at the ajaxStop function \$\endgroup\$ – Yi Jiang Feb 5 '11 at 13:14
0
votes
\$\begingroup\$

The answer that I was looking for, was very straight forward.

All was required was to put JQuery in synchronis mode by placing using

$.ajaxSetup({async:false});

and then doing the ajax calls using $.post("...

then just turning it on again

$.ajaxSetup({async:true});
\$\endgroup\$
  • 2
    \$\begingroup\$ You uh... do understand what synchronous mode does, right? There is a reason why ajax is asynchronous, a very good one. If you choose to use this, the browser will lock up waiting for the ajax to complete. Seriously, don't disable async unless you can live with that. \$\endgroup\$ – Yi Jiang Feb 15 '11 at 14:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.