js中有很多方式能够实现异步调用,将讨论他们及优缺点,四种调用方式rt。
脚本
将采用一个数组对象(records),通过异步调用的方式处理records,返回处理后的结果。
回调函数
回调函数是最普遍的异步执行的方案。回调函数类似于:
finder([1, 2], function(results) {
..do something
});
回调函数方式通过事后调用一个函数,上面的例子类似于:
Panel.show = function(name){
//do Something;
Panel.onshow[name]();
}
Setup
为能够更好的模拟find和process的过程,使用timers模拟AJAX方式进行处理。
function finder(records, cb) {
setTimeout(function () {
records.push(3, 4);
cb(records);
}, 1000);
}
function processor(records, cb) {
setTimeout(function () {
records.push(5, 6);
cb(records);
}, 1000);
}
回调函数方式
代码可能像下面这样:
finder([1, 2], function (records) {
processor(records, function(records) {
console.log(records);
});
});
将一个匿名函数出入finder函数中,在执行匿名函数时调用processor函数。
也可以使用如下代码
function onProcessorDone(records){
console.log(records);
}
function onFinderDone(records) {
processor(records, onProcessorDone);
}
finder([1, 2], onFinderDone);
log [1,2,3,4,5,6]。回调函数主要通过调用参数函数来实现。
事件处理函数(待续)
事件处理函数也是非常常见的异步调用,事件处理函数可能是
finder.on('done', function (event, records) {
..do something
});
Setup
给出一个事件处理函数的例子,这里还是借鉴callback的例子。
var finder = {
run: function (records) {
var self = this;
setTimeout(function () {
records.push(3, 4);
self.trigger('done', [records]);
}, 1000);
}
}
var processor = {
run: function (records) {
var self = this;
setTimeout(function () {
records.push(5, 6);
self.trigger('done', [records]);
}, 1000);
}
}
之后建立一个事件对象,包括on、trigger等方法
var eventable = {
on: function(event, cb) {
$(this).on(event, cb);
},
trigger: function (event, args) {
$(this).trigger(event, args);
}
}
然后利用extend方法,将eventable的方法复制给上面的对象
$.extend(finder, eventable);
$.extend(processor, eventable);
这样在finder和processor上可以监听事件的发生,
利用listener
finder.on('done', function (event, records) {
processor.run(records);
});
processor.on('done', function (event, records) {
console.log(records);
});
finder.run([1,2]);
最后输出
[1,2,3,4,5,6]
原文地址 http://sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/