Black
Black

Reputation: 5367

jQuery - coordinated event handler for array of $.post deferred objects

I have an $.each block that iterates over all the select elements on a form, and invokes a $.post for each one.

    var deferredObjects = [];

    $('#form').find('select').each(
        function(i, o) { 
            var jqxhr = $.post("data.json", {} )); 
            deferredObjects.push( jqxhr) ;
        }
    );    

I'd like to have an event-handler fire when all the post operations are complete. I'm collecting all the deferred objects returned from the post method into an array. I was hoping to use something like

 $.when( ... ).then( ... );

but I can't see how to fit this construct into my scenario?

Upvotes: 0

Views: 35

Answers (2)

Richard Ayotte
Richard Ayotte

Reputation: 5080

You can use the spread syntax like this.

$.when(...deferredObjects)

Upvotes: 1

maddy
maddy

Reputation: 136

You can use promise() (it will execute once all collective actions are done) available in jquery. For example, you can see

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>promise demo</title>
  <style>
  div {
    height: 50px;
    width: 50px;
    float: left;
    margin-right: 10px;
    display: none;
    background-color: #090;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>

<script>
$( "button" ).on( "click", function() {
  $( "p" ).append( "Started..." );

  $( "div" ).each(function( i ) {
    $( this ).fadeIn().fadeOut( 1000 * ( i + 1 ) );
  });

  $( "div" ).promise().done(function() {
    $( "p" ).append( " Finished! " );
  });
});
</script>

</body>
</html>

https://jsfiddle.net/mzo5Lhbk/

Also, read these links if you want to use when() https://api.jquery.com/jquery.when/

Hope it will help you!!!

Upvotes: 1

Related Questions