Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute scripts returned from .each() synchronously, but without delay in order of completion

The situation is that I am dynamically loading a set of scripts from an API that I then call via eval(). I don't care which order the scripts are called, but I don't want any of them to be called at the same time. That is, scripts A, B, and C can be returned in order C, B, A, and I want to begin eval(C) immediately when C is returned, but I want eval(B) to wait until eval(C) is completed.

Without getting into the fully hairy code, here is the heart of it where "instances" is a string array.

$.each(instances, function( index, instance ) {
    var apiUrl = "http://the-api-url.com/" + instance;
    $.getJSON(apiUrl, function(data) {
        // except I don't want to eval here as evaluations may overlap
        eval(data.script);
    });
}); 

From what I understand, I could use .when() to wait until all were complete, but that would waste time as I don't need to wait until all are downloaded in order to begin their execution.

like image 348
Brian Risk Avatar asked Nov 10 '15 13:11

Brian Risk


1 Answers

It's a bit unclear from your question, but assuming that the scripts can be executed in any order (A, B, C, A, C, B, B, A, C, etc.) then you don't have to change anything.

Javascript (in the browser) is single threaded, so the callbacks you are passing to $.getJSON will be scheduled serially.

like image 75
Sean Bright Avatar answered Sep 22 '22 00:09

Sean Bright