回调地狱:比如说请求a的数据了之后再去请求b的数据,请求到b的数据再去请求c的数据,多个回调函数嵌套的写法叫做回调地狱。
<script src="jquery.js"></script>
$.ajax({
url:"a.json",
dataType:"json",
success(data){
$.ajax({
url:"b.json",
dataType:"json",
success(data){
$.ajax({
url:"c.json",
dataType:"json",
success(data){
console.log(data)
}
})
}
})
}
})
Promise对象主要把回调函数嵌套的写法变成链式写法。
请求一个原生ajax;
function fun1(url){
return new Promise(function(resllove,seject){
var xhr=new XMLHttpRequest();
xhr.open("get",url,true);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var data=xhr.responseText;
resolve(data);
}else{
reject("404");
}
}
}
})
}
fun1("a.json").then(res=>{
console.log(res);
},res=>{
console.log(res);
})
请求jq版ajax;
<script src="jquery.js"></script>
<script>
function fun2(url,data){
return $.ajax({
url,
data,
dataType:"json",
})
}
fun2("a.json").then(res=>{
console.log(res);
//对数据进行操作
return fun2("b.json");
//需要返回一个promise对象,才能调用.then()方法;
}).then(res=>{
console.log(res);
})
</script>