Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Last active September 7, 2021 07:58
Show Gist options
  • Save dbrgn/c8b049826edbd5e274bd592c26a70029 to your computer and use it in GitHub Desktop.
Save dbrgn/c8b049826edbd5e274bd592c26a70029 to your computer and use it in GitHub Desktop.
TypeScript + async / await + throw
async function foo() {
await sleep(1000);
console.log(1);
await sleep(1000);
console.log(2);
console.log("throwing now");
if (1 == 1) {
throw "oh shitshit";
}
await sleep(1000);
console.log(3);
}
function sleep(ms = 0) {
return new Promise(r => setTimeout(r, ms));
}
foo().then(() => console.log('done'))
.catch((e) => console.log("Exception happened:", e));
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
function foo() {
return __awaiter(this, void 0, void 0, function* () {
yield sleep(1000);
console.log(1);
yield sleep(1000);
console.log(2);
console.log("throwing now");
if (1 == 1) {
throw "oh shitshit";
}
yield sleep(1000);
console.log(3);
});
}
function sleep(ms = 0) {
return new Promise(r => setTimeout(r, ms));
}
foo().then(() => console.log('done')).catch((e) => console.log("Exception happened:", e));
2016-05-18 15:55:24.969 VM277:12 1
2016-05-18 15:55:25.970 VM277:14 2
2016-05-18 15:55:25.970 VM277:15 throwing now
2016-05-18 15:55:25.970 VM277:26 Exception happened: oh shitshit
@tonfranco
Copy link

cool

@tvprasad
Copy link

tvprasad commented May 3, 2019

Nice work. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment