Skip to content

Instantly share code, notes, and snippets.

@dnafication
Last active October 9, 2020 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnafication/b4f2d6fd950433294732a9aa7253227f to your computer and use it in GitHub Desktop.
Save dnafication/b4f2d6fd950433294732a9aa7253227f to your computer and use it in GitHub Desktop.
function timeout(timeInMs, wontDo) {
return new Promise((resolve, reject) => {
if (wontDo === true) {
reject(Error("I wont do!"));
}
setTimeout(resolve(`timeout finished ${timeInMs}`), timeInMs);
});
}
async function A() {
// add true to second argument to make timeout fail/reject
// await timeout(300, true)
await timeout(300);
// throw Error('something bad')
console.log("done with A");
return "A";
}
async function B() {
try {
await timeout(100);
await A();
// throw Error('something bad')
console.log("done with B");
return "B";
} catch (error) {
console.error(`error in B: ${error}`);
// you can throw the error further down
// then this async function with reject or throw error.
// throw error
}
}
async function C() {
try {
await timeout(100);
await B();
// await A()
// throw Error('something bad')
console.log("done with C");
return "C";
} catch (error) {
console.error("error in C: ", error);
}
}
async function main() {
try {
await timeout(300);
await C();
console.log("done with main");
return "main";
} catch (error) {
console.error("error in main: ", error);
}
}
main()
.then(console.log)
.catch(console.error)
.finally(() => console.log("done"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment