在 while 函数中提前延迟循环

Advance deferred looping in while function

在 SO Deferred in $.when while looping an array

中扩展这个问题

我有这个控制结构:-

function oldSync(array) { 
  var output = []; // to store the output
  $.each( array, function(key,value) { // runs sequentially
    var item1 = SyncFunction_A(input);
    var item2 = SyncFunction_B(input); 
    output.push({'a': item1, 'b': item2});
  });
  return doSomething(output); // process all output
}

接下来,我将 SyncFunction() 替换为 AsyncFunction(),

问题:如何将其转换为延迟函数或异步函数?

function newAync(array) { //
  var output = [];
  $.each( array, function(key,value) { // runs sequentially
    var item1 = AsyncFunction_A(input);
    var item2 = AsncFunction_B(input); 
    item1.then(item2).then(function(data) {
        output.push({'a': data[0], 'b': data[1] });
    }
  });
  return doSomething(output); // FAIL, it doesn't wait for Async
}

实际上我更喜欢在沙盒中检查代码。但我希望你能抓住主要思想

function newAync(array) { //
  var output = [],
    promises = [];
  $.each( array, function(key,value) { // runs sequentially
    var item1 = AsyncFunction_A(input);
    var item2 = AsncFunction_B(input); 
    var promise = item1.then(item2).then(function(data) {
        output.push({'a': data[0], 'b': data[1] });
    };

    promises.push(promise);
  });

  var defer = $.Deferred();

  $.when.apply($, promises).done(function() {
    defer.resolve(doSomething(output));
  });

  return defer.promise();
}

您需要做的是利用回调函数来使用同步函数。我不知道你的 A 和 B 函数是什么,它们应该做什么,或者这些值代表你存储在 output 数组中的什么。

这是一个示例,您将 url 的数组传递给一个函数,并在您获得每个 url:

的结果时执行回调
function func(urls_array, callback){ // The "callback" will be called when all results have returned.
  var results = []; // Array to store the results of each $.get
  for(var i=0;i<urls_array.length;i++){ // Loop through each url
    $.get(urls_array[i], function(x){ // get the data at the url
      results.push(x); // store the results of this get function
      if(results.length == urls_array.length){ // If all urls have returned
        callback(results); // execute the callback function letting it know that you have finished
      }
    });
  }
}

也许这会帮助您了解同步函数(带回调函数)的工作原理。

如果您想更具体地了解您的问题,我们可以提供可能有帮助的答案,但您的问题过于笼统,而且可能无法为我们定义 SyncFunction_A 等内容.