3

I am working on a jQuery plugin with an add_record method (see below). If you look at the function definition, there are two $.each loops that append values to plugin.payload.

Right now, everything works fine. However, what if records or options is really big? Do I need to be concerned about the $.each() not finishing before the transmit call is issued?

If so, what is the best way to address the issue?

plugin.add_record = function (records, options, callback) {
    if (typeof (options) == "function") {
        callback = options;
        options = undefined;
    }
    if (options) {
        $.each(options, function (index, value) {
            plugin.payload.append($(value));
        });
    }
    $.each(records, function (index, value) {
        plugin.payload.append($(value));
    });
    transmit('API_AddRecord', plugin.payload, 'db', function (data) {
        return typeof (callback) == "function" ? callback(data) : data;
    });
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
doremi
  • 14,921
  • 30
  • 93
  • 148
  • possible duplicate of [Is jQuery "each()" function synchronous?](http://stackoverflow.com/questions/7371942/is-jquery-each-function-synchronous) – showdev Sep 13 '13 at 00:21

2 Answers2

7

$.each is synchronous, so there is no worry that the calls will not complete. The only time you would run into trouble is if starting something asynchronous inside the loop (like an ajax call).

user2246674
  • 7,621
  • 25
  • 28
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • And I've run into that issue A LOT over the last couple of days. Do you have, by chance, an example and/or a recommended pattern on how to handle that use case? (ajax inside each) – doremi Sep 13 '13 at 00:24
  • @doremi You need to keep track of it yourself. For example: http://stackoverflow.com/a/287212/573218 – John Koerner Sep 13 '13 at 00:27
  • 1
    @doremi I recommend using Promises/A (which is what `$.ajax` returns and jQuery calls [Deferred Objects](http://api.jquery.com/category/deferred-object/)). Then you can `$.when` over the results from `$.each` (that is, return each Promise in turn and use each-like-map). – user2246674 Sep 13 '13 at 00:28
1

No there is no need for concern, because $.each and .append() are synchronous functions.

In synchronous execution of statements only after completing the one statement it will move to the next one.

The only problem could come only if you are doing some async operation inside the loop like an ajax request/animation etc which you are not doing in this case

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531