简体   繁体   English

JavaScript 顺序异步函数调用

[英]JavaScript sequential async function calls

I have an array of functions, which making some logic asynchronously (eg ajax calls).我有一个函数数组,它们异步生成一些逻辑(例如 ajax 调用)。 How does look like function, which will sequentially call functions from array?函数看起来如何,它将从数组中顺序调用函数?

var saveHandlers = [];

saveHandlers.push(function () {
   var deferred = $.Deferred();

   setTimeout(function() {
      deferred.resolve();
   }, 2000);

   return deferred.promise();
});

saveHandlers.push(function () {
   var deferred = $.Deferred();

   setTimeout(function() {
      deferred.resolve();
   }, 2000);

   return deferred.promise();
});

$(function () {
    var $form = $('#form');

    $form
       .unbind('submit')
       .submit(function (e) {
          if (saveHandlers.length > 0) {
              $.when.apply(null, saveHandlers);
          }
          e.preventDefault();
       });
});

Write a function which calls you async function and takes the array index as an argument.编写一个函数,该函数调用异步函数并将数组索引作为参数。

In the callback for the async function, increment the index and (if you haven't got to the end of the array) call the function recursively with the new index.在异步函数的回调中,增加索引并(如果您还没有到达数组的末尾)使用新索引递归调用该函数。

var foo = [fun_a, fun_b, fun_c];

function bar(index) {
    index = index || 0;

    function callback() {
        if (foo[++index]) {
           bar(index);
        }
    };

    foo[index]().then(callback);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM