[英]Excecute JavaScript function after previous one completes
我想按特定顺序(如下所示)执行几个JavaScript函数,而不是等到上一个函数完成为止。 我已经尝试了很多方法。 有什么建议么? 非常感谢您的帮助,我已经坚持了很长时间。 提前致谢!
function savedSearch(e){
applySearch1("ColumnA");
applySearch2("ColumnB");
applySearch3("ColumnC");
applySearch4("ColumnD");
applySearch5("ColumnE");
applySearch6("ColumnF");
}
您应该在所有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
});
});
});
});
});
});
}
如果使用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(); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.