Last active
December 23, 2018 08:29
-
-
Save yanzhihong23/a6d1a3fbb7714bb397d01cfe1e4546a7 to your computer and use it in GitHub Desktop.
Promise.all handle exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fetchData(x) { | |
return new Promise((resolve, reject) => { | |
// mock | |
if (x == 3 || x == 4 || x == 5) { | |
reject('error'); | |
} else { | |
resolve(x); | |
} | |
}); | |
} | |
/** | |
* render page with an array | |
* @param {array} data | |
*/ | |
function render(data) { | |
// render logic ... | |
console.log(data); | |
} | |
/** | |
* TODO: implement this function | |
* fetch multiply requests simultaneous, and render the page with response data array. | |
* if more than 3 requests fails, don't do render. | |
* @param {number} n | |
*/ | |
function fetchAndRender(n) { | |
const arr = []; | |
for (let i = 0; i < n; i++) { | |
arr.push(fetchData(i)); | |
} | |
let count = 0; | |
return Promise.all( | |
arr.map(item => { | |
return item.catch(err => { | |
count++; | |
return err; | |
}); | |
}) | |
).then(res => { | |
if (count <= 3) { | |
render(res.filter(item => item !== 'error')); | |
return Promise.resolve(); | |
} else { | |
return Promise.reject(); | |
} | |
}); | |
} | |
fetchAndRender(10) | |
.then(() => { | |
console.log('render success'); | |
}) | |
.catch(() => console.log('render failed')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment