1.javascript异步编程之回调函数
function fn2(data){
alert(data)
}
function fn1(callback){
var data = 12+1;
callback && callback(data)//data是fn1的操作结果
}
fn1(fn2);
function fn2(total){
alert("执行完了fn1")
alert(total);
}
function fn1(arr,callback){
var total = arr.reduce(function(a,b,index,arr){
return a + b;
})
callback && callback(total)//data是fn1的操作结果
} fn1([1,2,3,4,5],fn2);
2.JavaScript异步编程之事件驱动
function fn1(arr){
var total = arr.reduce(function(a,b,index,arr){
return a+b;
})
fn1.trigger('done',total)
}
function fn2(total){
console.log("fn1执行完毕")
console.log(total)
}
_.extend(fn1,Backone.Events);
fn1.on('done',fn2);
fn1([1,2,3,4,5]);
3.JavaScript异步编程之发布订阅
function fn1(arr){
var total = arr.reduce(function(a,b,index,arr){
return a+b;
})
fn1.publish('done',total)
}
function fn2(total){
console.log("fn1执行完毕")
console.log(total)
}
$.subscribe("done",fn2);
fn1([1,2,3,4,5]);
4.JavaScript异步编程之Promise
function fn1(arr){
var dtd = $.Deferred();
window.setTimeout(function(){
var total = arr.reduce(function(a,b,index,arr){
return a+b;
})
dtd.resolve(total);
},1000)
return dtd
}
function fn2(total){
console.log("fn1执行完毕")
console.log(total)
}
fn1([1,2,3,4,5]).then(fn2);