<!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>处理多个Promise</title>
</head>
<body>
<script>
/*
Promise.all() 方法回傳一個 Promise 物件,當引數 iterable 中所有的 promises 都被實現(resolved)。
或以第一個被拒絕的 promise 的原因被拒絕。
*/
//reslove
const usersPromise=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove(['Simba','PumbaaPig','NANA'])
},2000);
})
const moviePromise=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove({name:'狮子王',rating:8.9,year:2019})
},600)
});
Promise
.all([usersPromise,moviePromise])
.then(responses=>{
const [users,movide]=responses;
console.log(users);//(3) ["Simba", "PumbaaPig", "NANA"]
console.log(movide);//{name: "狮子王", rating: 8.9, year: 2019}
})
//reject
const usersPromise1=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove(['Simba','PumbaaPig','NANA'])
},2000);
})
const moviePromise1=new Promise((reslove,reject)=>{
setTimeout(()=>{
reject(Error('NO movie'));
},600)
});
Promise
.all([usersPromise1,moviePromise1])
.then(responses=>{
const [users1,movide1]=responses;
console.log(users1);//(3) ["Simba", "PumbaaPig", "NANA"]
console.log(movide1);//NO movie
})
/*
Promise.race(iterable) 方法返回一个 promise,一旦迭代器中的某个promise解决或拒绝,
返回的 promise就会解决或拒绝。
*/
//谁快就打印谁
const usersPromise2=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove(['Simba','PumbaaPig','NANA'])
},2000);
})
const moviePromise2=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove({name:'狮子王',rating:8.9,year:2019})
},600)
})
Promise
.race([usersPromise2,moviePromise2])
.then(responses=>{
console.log(responses);//{name: "狮子王", rating: 8.9, year: 2019}
})
.catch(err=>{
console.error(err);
})
//有错误也是一样的,还是不能影响谁快就打印谁的定律
const usersPromise3=new Promise((reslove,reject)=>{
setTimeout(()=>{
reject(Error('拒绝、错误'))
},2000);
})
const moviePromise3=new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove({name:'狮子王',rating:8.9,year:2019})
},600)
})
Promise
.race([usersPromise3,moviePromise3])
.then(responses=>{
console.log(responses);//{name: "狮子王", rating: 8.9, year: 2019}
})
.catch(err=>{
console.error(err);
})
</script>
</body>
</html>