回调:回调是一个函数被作为一个参数传递到另一个函数里,在那个函数执行完后再执行(存在同步、异步)
同步回调:
function A(callback){
console.log("I am A");
callback(); //调用该函数
}
function B(){
console.log("I am B");
}
A(B); // I am A I am B
异步回调:
因为Javascript语言的执行环境是"单线程",但是有很多情况的执行步骤(ajax请求远程数据,IO等)是非常耗时的,
如果一直单线程的堵塞下去会导致程序的等待时间过长页面失去响应,影响用户体验。常用的异步回调方法:
1、ajax $.when
1) 指定同一ajax操作的多个回调函数
$.ajax("test.html")
.done(function(){ alert("哈哈,成功了!");} )
.fail(function(){ alert("出错啦!"); } )
.done(function(){ alert("第二个回调函数!");} );
允许自由添加多个回调函数,它们按照添加顺序执行
2) 为多个ajax操作指定回调函数
$.when($.ajax("test1.html"), $.ajax("test2.html"))
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });
先执行两个操作$.ajax("test1.html")和$.ajax("test2.html"),如果都成功了,就运行done()指定的回调函数;如果有一个失败或都失败了,就执行fail()指定的回调函数。
3) 普通操作的回调函数接口
//$.when()的参数只能是deferred对象,所以wait()进行改写
var dtd = $.Deferred(); // 新建一个deferred对象
var wait = function(dtd){
var tasks = function(){
alert("执行完毕!");
dtd.resolve(); // 改变deferred对象的执行状态
};
setTimeout(tasks,5000);
return dtd;
};
//wait()函数运行完,就会自动运行done()方法指定的回调函数
$.when(wait(dtd))
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });
2、Promises: 一套异步操作处理机制
promise 状态:
pending:初始状态,既不是成功,也不是失败状态
resolve: 操作成功
rejected:操作失败
var promiseObj = new Promise(function(resolve,reject){
setTimeout(function(){
resolve('foo');
},300);
});
promiseObj.then(function(value){
console.log(value); // foo
});
3、async await
async 异步:用于申明一个 异步的function(返回一个promise 对象)
await 等待:用于等待一个异步任务执行完成的的结果( await 只能出现在 async 函数中)
参考文章:JavaScript Promise迷你书(中文版)
用 async/await 来处理异步
js async await 终极异步解决方案