很方便的捕获错误
创建Promise
//用定时器模拟异步请求
function getData(x){
return new Promise((resolve, reject)=>{
setTimeout(function(){
if(x){
resolve(x)
}else{
reject('404')
}
},Math.random()*1000+1)
})
}
Promise.prototype.then
getData(1)
.then(function(x){
console.log(x)
return getData(2)
}, e=>{console.log(e)})
.then(function(x){
console.log(x)
return getData(3)
}, e=>{console.log(e)})
.then(function(x){
console.log(x)
}, e=>{console.log(e)})
then方法接受两个函数(注意是函数,不要直接调用函数,调用的函数会立即执行
成功的时候执行第一个函数,失败的时候执行第二个函数
Promise.all
当我们需要获得多个数据才进行下一步时使用Promise.alllet group = Promise.all([getData(22),getData(66),getData(1024),getData(-33)])
group.then(
function(arr){
let sum = 0
arr.forEach(item => sum+=item)
console.log(sum)
},e => {console.log(e)}).catch(e=>{console.log(e)})
Promise.all需要传入一个数组,数组中的元素都是Promise对象,当这些对象都执行成功,执行then中的第一个函数(成功函数),失败时只能获得第一个失败Promise的错误数据
Promise.all是大家一起到终点,一个失败全都失败
Promise.race
let group2 = Promise. race([getData(22),getData(),getData(1024),getData(-33)])
group2.then(
function(arr){
console.log(`我拿到数据了!${arr}`)
},e => {console.log(e)})
Promise.race和Promise.all相对应,哪个Promise对象最快得到结果,就最先用谁的结果(只要快就行,不管失败还是成功)