1import { 2 isArray 3} from "../utils"; 4 5/** 6 `Promise.race` returns a new promise which is settled in the same way as the 7 first passed promise to settle. 8 9 Example: 10 11 ```javascript 12 let promise1 = new Promise(function(resolve, reject){ 13 setTimeout(function(){ 14 resolve('promise 1'); 15 }, 200); 16 }); 17 18 let promise2 = new Promise(function(resolve, reject){ 19 setTimeout(function(){ 20 resolve('promise 2'); 21 }, 100); 22 }); 23 24 Promise.race([promise1, promise2]).then(function(result){ 25 // result === 'promise 2' because it was resolved before promise1 26 // was resolved. 27 }); 28 ``` 29 30 `Promise.race` is deterministic in that only the state of the first 31 settled promise matters. For example, even if other promises given to the 32 `promises` array argument are resolved, but the first settled promise has 33 become rejected before the other promises became fulfilled, the returned 34 promise will become rejected: 35 36 ```javascript 37 let promise1 = new Promise(function(resolve, reject){ 38 setTimeout(function(){ 39 resolve('promise 1'); 40 }, 200); 41 }); 42 43 let promise2 = new Promise(function(resolve, reject){ 44 setTimeout(function(){ 45 reject(new Error('promise 2')); 46 }, 100); 47 }); 48 49 Promise.race([promise1, promise2]).then(function(result){ 50 // Code here never runs 51 }, function(reason){ 52 // reason.message === 'promise 2' because promise 2 became rejected before 53 // promise 1 became fulfilled 54 }); 55 ``` 56 57 An example real-world use case is implementing timeouts: 58 59 ```javascript 60 Promise.race([ajax('foo.json'), timeout(5000)]) 61 ``` 62 63 @method race 64 @static 65 @param {Array} promises array of promises to observe 66 Useful for tooling. 67 @return {Promise} a promise which settles in the same way as the first passed 68 promise to settle. 69*/ 70export default function race(entries) { 71 /*jshint validthis:true */ 72 let Constructor = this; 73 74 if (!isArray(entries)) { 75 return new Constructor((_, reject) => reject(new TypeError('You must pass an array to race.'))); 76 } else { 77 return new Constructor((resolve, reject) => { 78 let length = entries.length; 79 for (let i = 0; i < length; i++) { 80 Constructor.resolve(entries[i]).then(resolve, reject); 81 } 82 }); 83 } 84} 85