Asynchronous for cycle in JavaScript

前端 未结 13 1237
温柔的废话
温柔的废话 2020-11-22 11:37

I need a loop that waits for an async call before continuing. Something like:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    //         


        
13条回答
  •  日久生厌
    2020-11-22 11:59

    We can also use help of jquery.Deferred. in this case asyncLoop function would look like this:

    asyncLoop = function(array, callback) {
      var nextElement, thisIteration;
      if (array.length > 0) nextElement = array.pop();
      thisIteration = callback(nextElement);
      $.when(thisIteration).done(function(response) {
        // here we can check value of response in order to break or whatever
        if (array.length > 0) asyncLoop(array, collection, callback);
      });
    };
    

    the callback function will look like this:

    addEntry = function(newEntry) {
      var deferred, duplicateEntry;
      // on the next line we can perform some check, which may cause async response.
      duplicateEntry = someCheckHere();
      if (duplicateEntry === true) {
        deferred = $.Deferred();
        // here we launch some other function (e.g. $.ajax or popup window) 
        // which based on result must call deferred.resolve([opt args - response])
        // when deferred.resolve is called "asyncLoop" will start new iteration
        // example function:
        exampleFunction(duplicateEntry, deferred);
        return deferred;
      } else {
        return someActionIfNotDuplicate();
      }
    };
    

    example function that resolves deferred:

    function exampleFunction(entry, deffered){
      openModal({
        title: "what should we do with duplicate"
        options: [
           {name:"Replace", action: function(){replace(entry);deffered.resolve(replace:true)}},
           {name: "Keep Existing", action: function(){deffered.resolve(replace:false)}}
        ]
      })
    }
    

提交回复
热议问题