Skip to content

Instantly share code, notes, and snippets.

@onosendi
Created June 8, 2023 15:56
Show Gist options
  • Save onosendi/d4bf3313d1a2d4b54292f52e0be1281e to your computer and use it in GitHub Desktop.
Save onosendi/d4bf3313d1a2d4b54292f52e0be1281e to your computer and use it in GitHub Desktop.
// Function abstraction of try/catch
const fetch = () => new Promise((resolve, reject) => {
setTimeout(() => {
const fn = Math.floor(Math.random() * 2) % 2 ? resolve : reject;
fn('Foo');
}, 100);
});
const test = (trial) => ({
orElse: async (backup) => {
try {
return await trial();
} catch (error) {
return backup(error);
}
},
});
async function main() {
const foo = test(fetch);
const ps = Array.from({ length: 20 }, () => foo.orElse((e) => `Error ${e}`));
const res = await Promise.all(ps);
console.log(res);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment