Jon Wells
Jon Wells

Reputation: 4259

JQuery Array of Deferreds, implementation not working

can anyone see any mistakes in this code? I use this approach throught my application, almost identically, but for some reason I simply cannot seem to resolve the main promise "a";

   Parser.prototype.insertSomeData = function(data)
    {
        var a = $.Deferred(),
            table = "Example",
            columns = ["col1", "col2", "col3"];

        var deferreds = [];

        // insert Data into the database
        for (var i = 0; i < data.length; i++)
        {
            var dfd = $.Deferred();

            deferreds.push(dfd.promise());

            item = data[i];

            database.insert(table, columns, [item.one, item.two, item.three], function(){console.log("resolved"); dfd.resolve()}, dfd.reject);
        }
        $.when.apply(null, deferreds).then(function(){console.log("it worked!"); a.resolve()});

        return a.promise();
    }

both the promises in the deferred array do get resolved. So I think the problem is in the when Any see something I'm missing?

Upvotes: 1

Views: 165

Answers (2)

pimvdb
pimvdb

Reputation: 154968

  1. You coded dfd.resolve but this doesn't do anything more than just getting the function. You'd have to call it: dfd.resolve().
  2. When all deferreds are finished, you probably want to resolve a, not dfd. When $.when has finished, all dfds have been resolved, and you probably want to resolve the master deferred (a) in that case.

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108530

deferreds only contains promises from the dfd object, so they are the ones getting resolved.

Upvotes: 0

Related Questions