Promise.race()
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(),实现一样的效果: