Lukas
Lukas

Reputation: 7734

How to check each() iteration ends with promise()

I have some each iteration by data response from some jquery post action. My question is how to check that this itaration ends?

$.each(data, function(key, value){
//
}).promise().done(function(){
    setTimeout(function(){
        submitBtn.removeClass('buttonInProgress');
    }, time);
});

This is my code, what is wrong? I have an error undefined is not a function.

Upvotes: 2

Views: 1672

Answers (1)

user229044
user229044

Reputation: 239250

If you're doing some asynchronous action inside the .each callback, it's up to you to build a set of promises, and use $.when to wait for them all to resolve. It's also up to you to manually resolve each promise created inside your .each callback.

The process will look something like this:

var promises = [];

$.each(data, function () {
  var dfd = $.Deferred();

  doSomethingAsync({success: function () { dfd.resolve() });

  promises.push(dfd);
});

$.when.apply($, promises).then(function () {
  setTimeout(function(){
    submitBtn.removeClass('buttonInProgress');
  }, time);
});

Upvotes: 1

Related Questions