Skip to content

Instantly share code, notes, and snippets.

@yanzhihong23
Last active December 23, 2018 08:29
Show Gist options
  • Save yanzhihong23/a6d1a3fbb7714bb397d01cfe1e4546a7 to your computer and use it in GitHub Desktop.
Save yanzhihong23/a6d1a3fbb7714bb397d01cfe1e4546a7 to your computer and use it in GitHub Desktop.
Promise.all handle exceptions
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