上一个完成后执行JavaScript函数

时间:2015-06-06 00:23:38

标签: javascript jquery asynchronous synchronous jquery-callback

我想按特定顺序执行多个JavaScript函数(如下所示),直到上一个函数完成为止。我尝试过这么多方法。有什么建议?任何帮助都非常感激,我已经坚持这么久了。提前谢谢!

not

3 个答案:

答案 0 :(得分:2)

要添加以回应Mohkhan的其他答案,您还可以使用async库。

https://github.com/caolan/async

这将使您远离callback hell,并使更容易阅读的功能列表。

答案 1 :(得分:1)

您应该在所有applySearch *函数中使用回调。 像这样。

function savedSearch(e){
   applySearch1("ColumnA", function(){
       applySearch2("ColumnB", function(){
           applySearch3("ColumnC", function(){
               applySearch4("ColumnD", function(){
                   applySearch5("ColumnE",function(){
                       applySearch6("ColumnF", function(){
                           // You are done
                       });
                   });
               });
           });
       });
   });
}

答案 2 :(得分:0)

如果使用jquery,它有延迟的对象,可以帮助你处理异步函数。

以下是一个例子:

// Code goes here
$(document).ready(function() {
  function Pipe() {

    this.asyncTasks = [];
    this.observers = {};

    this.on = function(eventName, fn) {
      if (!this.observers[eventName]) {
        this.observers[eventName] = $.Callbacks;
      }
      this.observers[eventName].add(fn);
    }

    this.fire = function(eventName, data) {
      if (this.observers[eventName]) {
        this.observers[eventName].fire(data);
      }
    }

    this.register = function(asyncFn, context) {
      this.asyncTasks.push(new Task(asyncFn, context));
    }

    this.start = function() {
      this.fire('start');
      this._next();
    }

    this._next = function() {
      var task = this.asyncTasks.shift();
      if (task) {
        task.execute().then($.proxy(this._next, this));
      } else {
        this.fire('end');
      }
    }

    var Task = function(fn, context) {
      this.fn = fn;
      this.context = context;
      this.execute = function() {
        if (!this.fn) {
          throw new Exception("Failed to execute.");
        }
        var promise = this.fn.call(context);
        this.fn = null;
        return promise;
      }
    }
  }

  var bookMoview = function() {
    var dfd = jQuery.Deferred();

    // Resolve after a random interval
    setTimeout(function() {
      dfd.resolve("The movie is booked");
      console.log("The movie is booked");
    }, Math.floor(400 + Math.random() * 2000));

    // Return the Promise so caller can't change the Deferred
    return dfd.promise();
  }

  var bookTaxi = function() {
    var dfd = jQuery.Deferred();

    // Resolve after a random interval
    setTimeout(function() {
      console.log("Taxi is booked");
      dfd.resolve("Taxi is booked");
    }, Math.floor(400 + Math.random() * 2000));

    // Return the Promise so caller can't change the Deferred
    return dfd.promise();
  }

  var pipe = new Pipe();
  pipe.register(bookMoview);
  pipe.register(bookTaxi);
  pipe.start();

});