PROMISE:承诺:承诺本身(正在进行时),成功,失败
问题:当前有三个接口,要求,使用ajax请求三个接口,最终要在一个方法中拿到三个接口返回的数据?
方法1:回调地域
ajax({ url:url1, success:function(res1){ ajax({ url:url2, success:function(res2){ ajax({ url:url3, success:function(res3){ fn(res1,res2,res3) } }) } }) } }) function fn(res1,res2,res3){ console.log(res1,res2,res3) }
方法2:利用promise
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
// Promise改造ajax,实现,多请求,成功之后拿到所有数据
// 不使用回调地域
function ajax(url){
var p = new Promise(function(s,e){//执行promise中的成功和失败,ajax中的成功和失败参数就不用写了。
var xhr = new XMLHttpRequest();
xhr.open("get",url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
s(xhr.responseText)
}else if(xhr.readyState == 4 && xhr.status != 200){
e(xhr.status)
}
}
xhr.send();
})
return p; //必须要return,因为是在ajax这个函数中
}
var p1 = ajax(""); //第一个promise对象
var p2 = ajax(""); //第二个promise对象
var p3 = ajax(""); //第三个promise对象
Promise.all([p1,p2,p3]).then(function(res){ //将p1,p2,p3都传入Promise.all要用数组的形式。都成通过then。都成功,执行第一个回调函数。
console.log(res) //自动放在数组里。["hello1","hello2","hello3"]
},function(res){
console.log(res) //有一个失败就返回错误的信息
})
</script>
</html>
利用计时器模仿ajax;使用promise处理
var p = new Promise(function(success,error){ // 正在进行时... // ajax的正在请求... // 如果ajax成功了,这里用计时器模拟ajax。若第一个随机时间段免责说明他执行成功了。第二个端,说明执行失败了。计时器没被清空,只是方法被清空了。只能有一个状态。 setTimeout(() => { // console.log(1) success(); }, Math.random()*1000); // 如果ajax失败了 setTimeout(() => { // console.log(2) error(); }, Math.random()*1000); }); // 承诺的后续,然后呢?then的第一个参数,成功的函数,第二个参数,失败的函数 p.then(function(){ console.log("成功") },function(){ console.log("失败") })