Promise.race([ ])---race競賽,只要有一個決議了,就返回一個promise實例(對應resolve()或reject( )中參數值;
1、與Promise.all()對應的,還有一個 Promise.race()方法,接受的也是個數組,里面也都是Promise實例。
---數組中有一個promise實例決議為成功或失敗,Promise.race()也會決議為成功或失敗,將對應的值(參數)傳遞過來;
2、Promise.race([ ])中數組為空數組,就不會執行,永遠掛起;*******與all方法相反;
1、成功時:
//Promise.race( [promise1, promise2]) : Promise //Promise.race()接收的也都是數組,數組項也都是promise實例, //只有數組中有一項決議為成功或者失敗,Promise.race也會返回對應的成功或者失敗,並把值傳遞過來 //也就是說看決議哪個速度快,就返回的是誰 function getData1(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第一條數據加載成功') resolve('data1') },500) }) } function getData2(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第二條數據加載成功') resolve('data2') },1000) }) } function getData3(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第三條數據加載成功') resolve('data3') },1000) }) } let p = Promise.race( [getData1(), getData2(), getData3() ]); p.then(data => { console.log(data) //打印結果為data1 })
打印結果為:

2、如果是reject:
function getData1(){
return new Promise( (resolve, reject) => {
setTimeout( () => {
console.log('第一條數據加載成功')
reject('err')
},500)
})
}
function getData2(){
return new Promise( (resolve, reject) => {
setTimeout( () => {
console.log('第二條數據加載成功')
resolve('data2')
},1000)
})
}
function getData3(){
return new Promise( (resolve, reject) => {
setTimeout( () => {
console.log('第三條數據加載成功')
resolve('data3')
},1000)
})
}
let p = Promise.race( [getData1(), getData2(), getData3() ]);
p.then(data => {
console.log(data)
}, e => {
console.log(e) //打印結果為err
})
打印結果為:

3、如果為空數組
function getData1(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第一條數據加載成功') reject('err') },500) }) } function getData2(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第二條數據加載成功') resolve('data2') },1000) }) } function getData3(){ return new Promise( (resolve, reject) => { setTimeout( () => { console.log('第三條數據加載成功') resolve('data3') },1000) }) } let p = Promise.race( [ ]); p.then(data => { console.log(data) }, e => { console.log(e) })
打印結果為空:

如果不使用promise.race(),實現一樣的效果:

