1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(88); }, 1000); }); const promise2 = new Promise((resolve, reject) => { setTimeout(() => { reject("error"); }, 500); });
const myPromiseRace = (array) => { let results = ""; return new Promise((resolve, reject) => { for (let index in array) { if (array[index] instanceof Promise) { array[index].then( array[index].then( (res) => { results = res; resolve(results); }, (err) => { reject(err); } ) ); } else { results = array[index]; resolve(results); } } }); };
let arr = [promise1, promise2];
myPromiseRace(arr) .then((res) => { console.log(res, "res"); }) .catch((err) => { console.log(err, "err"); });
let arr1 = [promise1, promise2, 3, 4];
myPromiseRace(arr1) .then((res) => { console.log(res, "res"); }) .catch((err) => { console.log(err, "err"); });
|