function createPromises(length) {
const promises = [];
for (let i = 0; i < length; i += 1) {
const value = Math.random();
promises.push(new Promise((resolve, reject) => setTimeout(() => {
if (value < 0.1) reject('exception');
resolve(value);
}, value * 1000)));
}
return promises;
}
async function resolver(array) {
const results = array.map(async (promise) => {
try {
const result = await promise;
return result;
} catch (err) {
return 0;
}
});
return results;
}
async function sum(promises) {
try {
const promised = await resolver(promises);
const results = await Promise.all(promised);
return console.log(results.reduce((a, i) => {
a += i;
return a;
}, 0));
} catch(err) {
return console.log(err.stack || err);
}
}
sum(createPromises(100));
Created
July 8, 2019 18:06
-
-
Save peterdee/fc5d4ec1b447f886fee8473b8829d16f to your computer and use it in GitHub Desktop.
Some promisification with error handling
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment