异步js调用:callback,listeners,control flow libs 和 promises

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值