Async pending tasks with jQuery

I am new to JavaScript deferred classes and would like to implement a function that will iterate over forms and submit them one at a time.

It seems that deferred classes are a way to do this.

I tried to execute this answer , but for some reason my implementation starts, waits 3 seconds and ends. I want it to show a different form name every 3 seconds until it ends with all the forms that then ended.

What am I doing wrong? JSFIDDLE

function syncAll() {
        
  var promises = [];
  var forms = [
    {'name':'form 1'},
    {'name':'form 2'},
    {'name':'form 3'}, 
    {'name':'form 4'}];

  $.each(forms, function (index, value) {
    var def = new $.Deferred();
    setTimeout(function () {
      $("#output").html("Syncing: " + value.name);
      def.resolve({ 'message': 'finito!' });
    }, 3000);
    promises.push(def);

  });

  return $.when.apply(undefined, promises).promise();
}
    
    
    $.when(syncAll()).done(function(response){
        $("#output").html(response.message);
    });
    /*
    syncAll().done(function (response) {
      $("#output").html(response.message);
    }));
    */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">Start</div>
Run code
+4
source share
1 answer

JSFiddle: https://jsfiddle.net/TrueBlueAussie/v6cgak1u/2/

promise = promise.then(functionReturningNextPromise):

function syncAll() {
    var promise = $.when();  // Start with a resolved promise.
    var forms = [
      {'name':'form 1'},
      {'name':'form 2'},
      {'name':'form 3'}, 
      {'name':'form 4'}];

    $.each(forms, function (index, value) {
        promise = promise.then(function(){
            var def = $.Deferred();
            setTimeout(function () {
                $("#output").html("Syncing: " + value.name);
                def.resolve({ 'message': 'finito!' });
            }, 3000);
            return def.promise();
        });
    });
    return promise;
}


$.when(syncAll()).done(function(response){
    $("#output").html(response.message);
});

, setTimeout , ( setTimeout).

, new $.Deferred()

:

javascript jQuery , :

function syncAll() {
    var forms = [
        {'name':'form 1'},
        {'name':'form 2'},
        {'name':'form 3'}, 
        {'name':'form 4'}
    ];
    return forms.reduce(function(promise, value) {
        return promise.then(function() {
            return $("#output").delay(1000).html("Syncing: " + value.name).promise();
        });
    }, $.when()).then(function() {
        return {'message': 'finito!'};
    });
}

syncAll().then(function(response) {
    $("#output").html(response.message);
});

, , :

+5

Source: https://habr.com/ru/post/1663240/


All Articles