回调地狱(callback hell)和Promise
什么是callback hell
关于callback hell(回调地狱)说白了就是回调函数中嵌套着回调函数。在异步操作总比较常见,node.js尤其受改问题困扰。
$(function(){
$("#btn").click(function(){
$.ajax({
url:"post.php",
method:"get",
success:function(res){
},
error:function(){
},
timeout:3000
})
})
})
上面代码中就有多个回调函数的嵌套。有个笑话,某特工潜入秘密机构,打开其机密node.js代码最后几行,发现这么几行
});
});
});
});
});
});
});
});
});
});
});
Promise对象
有许多第三方库致力于解决回调地狱,但都不近如人意。 ECMA6中新增了Promise对象,提供了对异步的解决方案。
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
下面是一个用Promise实现aja加载的例子
var getJSON = function(url) {
var promise = new Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
function handler() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
});
return promise;
};
getJSON("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}, function(error) {
console.error('出错了', error);
});
jquery 中的 promise
jquery 中也具有promise的用法
function get(){
$.ajax({
url:'test.php'
}).then(function(){
return $.ajax({ url:'test1.php' });
}).then(function(){
return $.ajax({ url:'test2.php' });
}).then(function(){
return $.ajax({ url:'test3.php' });
}).then(function(){
//TODO here
});
}
for(i=0;i<list.length;i++){
get()
}
(完)