Question

I have the following function which queries a SQLite database and pushed results into an Array that is used later. I need to wait for the each statement to process the tables in the (self.projectSetEditList) However it seems that the master deferred is not waiting for all promises... Am I just going about this all wrong? I need to know when all the sql results are ready before proceeding to the next function.

/// <summary>Validates user INSERTS to project_set entities</summary>
this.initProjectSetAdds = function ()
{
    var promises = [];
    var masterDeferred = new $.Deferred();

    ///var count = (self.projectSetEditList.length - 1);
    $.each(self.projectSetEditList, function (index, syncEntity)
    {
        var def = new $.Deferred();
        //get the config entity definition object
        var entityDefinition = self.getEntityDefinition(syncEntity.entity_name);
        self.db.executeSql(self.getAddsSql(entityDefinition)).done(function (tx, insertResults)
        {
            self.projectSetAdds.push({ definition: entityDefinition, addedObjects: dataUtils.convertToObjectArray(insertResults) });
            def.resolve(true);
        });
        promises.push(def);
    });

    //resolve all deferred and return to caller
    $.when.apply($, promises).then(function ()
    {
        masterDeferred.resolve(arguments);
    },
    function ()
    {
        masterDeferred.reject(arguments);
    });

    return (masterDeferred.promise());
}

The only async function inside is executeSql... Any suggestions are greatly appreciated

Was it helpful?

Solution

Your code appears unnecessarily complicated to me.

Since $.when also creates a promise, don't bother creating the masterDeferred yourself, just do:

return $.when.apply($, promises);

The only functional difference is that this version will pass the true results as individual parameters to the eventual callback, whereas your code will pass a single array of [true, true, ...] values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top