manutenfruits
manutenfruits

Reputation: 1577

Loop with Deferred objects and promises

I have the following code

    $.when(tableInsert("index.php/get/sync/riesgos", insert_riesgo, evalua.webdb.db, callback)).then(function(){
        update_records("riesgos");
        $.when(tableInsert("index.php/get/sync/estancias", insert_estancia, evalua.webdb.db, callback)).then(function(){
            update_records("estancias");
            $.when(tableInsert("index.php/get/sync/riesgosestancias", insert_riesgoestancia, evalua.webdb.db, callback)).then(function(){
                update_records("riesgosestancias");
            });
        });
    });

I am trying to find how to integrate it inside of a for loop or a $.each loop, so that it waits for the promise to be done before the next iteration. At first it looks like three calls would be easier to be nested, but this is only a piece of code, the nested calls count 15 now!

Upvotes: 1

Views: 2877

Answers (3)

Kernel James
Kernel James

Reputation: 4074

If you are into the whole async Deferred thing:

var arr = [
  ["index.php/get/sync/riesgos", insert_riesgo, "riesgos"],
  ["index.php/get/sync/estancias", insert_estancia, "estancias"],
  ["index.php/get/sync/riesgosestancias", insert_riesgoestancia, "riesgosestancias"]
];

var dfd = $.Deferred().resolve();

$.each(arr, function(i, item) {
  dfd.then(function() {
    return $.when(tableInsert(item[0], item[1], evalua.webdb.db, callback)
    .then(function() {
      update_records(item[2]);
    });
  })
});

Upvotes: 0

manutenfruits
manutenfruits

Reputation: 1577

I've been thinking before seeing your answer, @felix-kling and came to a similar approach:

Make an array:

webdb.tables=[{
    name: "riesgos",
    callback: insert_riesgo,
},{
    name: "estancias",
    callback: insert_estancia,
},{
    name: "riesgosestancias",
    callback: insert_riesgoestancia,
}];

And using a recursive function loop through it:

var i=0;
    function recursive(){
        $.when(tableInsert("index.php/get/sync/"+webdb.tables[i].name, webdb.tables[i].callback, webdb.db, callback)).then(function(){
            update_records(webdb.tables[i].name);
            if(++i<webdb.tables.length)
                recursive();
        });
    }

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817238

Well, you need an array with the data first, for example:

var calls = [
    {
        url: "index.php/get/sync/riesgos",
        func: insert_riesgo,
        update: "riesgos"
    },
    ...
];

and then you can chain the calls using .pipe [docs]:

var def = (new $.Deferred()).resolve();

$.each(calls, function(call) {
    def = def.pipe(function() {
        return tableInsert(call.url, call.func, evalua.webdb.db, callback).done(function() {
            update_records(call.update);
        ]);
    });
});

There is no need for $.when in your example.

Upvotes: 5

Related Questions