Async Await

A PRO egghead video course that covers the same material

As a thought experiment imagine the following: a way to tell the JavaScript runtime to pause the executing of code on the await keyword when used on a promise and resume only once (and if) the promise returned from the function is settled:

  1. // Not actual code. A thought experiment
  2. async function foo() {
  3. try {
  4. var val = await getMeAPromise();
  5. console.log(val);
  6. }
  7. catch(err) {
  8. console.log('Error: ', err.message);
  9. }
  10. }

When the promise settles execution continues,

  • if it was fulfilled then await will return the value,
  • if it’s rejected an error will be thrown synchronously which we can catch.

This suddenly (and magically) makes asynchronous programming as easy as synchronous programming. Three things needed for this thought experiment are:

  • Ability to pause function execution.
  • Ability to put a value inside the function.
  • Ability to throw an exception inside the function.

This is exactly what generators allowed us to do! The thought experiment is actually real and so is the async/await implementation in TypeScript / JavaScript. Under the covers it just uses generators.

Generated JavaScript

You don’t have to understand this, but it’s fairly simple if you’ve read up on generators. The function foo can be simply wrapped up as follows:

  1. const foo = wrapToReturnPromise(function* () {
  2. try {
  3. var val = yield getMeAPromise();
  4. console.log(val);
  5. }
  6. catch(err) {
  7. console.log('Error: ', err.message);
  8. }
  9. });

where the wrapToReturnPromise just executes the generator function to get the generator and then use generator.next(), if the value is a promise it would then+catch the promise and depending upon the result call generator.next(result) or generator.throw(error). That’s it!

Async Await Support in TypeScript

Async - Await has been supported by TypeScript since version 1.7. Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.
It was only supported for target es6 transpiling directly to ES6 generators.

TypeScript 2.1 added the capability to ES3 and ES5 run-times, meaning you’ll be free to take advantage of it no matter what environment you’re using. It’s important to notice that we can use async / await with TypeScript 2.1 and many browsers are supported, of course, having globally added a polyfill for Promise.

Let’s see this example and take a look at this code to figure out how TypeScript async / await notation works:

  1. function delay(milliseconds: number, count: number): Promise<number> {
  2. return new Promise<number>(resolve => {
  3. setTimeout(() => {
  4. resolve(count);
  5. }, milliseconds);
  6. });
  7. }
  8. // async function always returns a Promise
  9. async function dramaticWelcome(): Promise<void> {
  10. console.log("Hello");
  11. for (let i = 0; i < 5; i++) {
  12. // await is converting Promise<number> into number
  13. const count:number = await delay(500, i);
  14. console.log(count);
  15. }
  16. console.log("World!");
  17. }
  18. dramaticWelcome();

Transpiling to ES6 (—target es6)

  1. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  2. return new (P || (P = Promise))(function (resolve, reject) {
  3. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  6. step((generator = generator.apply(thisArg, _arguments || [])).next());
  7. });
  8. };
  9. function delay(milliseconds, count) {
  10. return new Promise(resolve => {
  11. setTimeout(() => {
  12. resolve(count);
  13. }, milliseconds);
  14. });
  15. }
  16. // async function always returns a Promise
  17. function dramaticWelcome() {
  18. return __awaiter(this, void 0, void 0, function* () {
  19. console.log("Hello");
  20. for (let i = 0; i < 5; i++) {
  21. // await is converting Promise<number> into number
  22. const count = yield delay(500, i);
  23. console.log(count);
  24. }
  25. console.log("World!");
  26. });
  27. }
  28. dramaticWelcome();

You can see full example here.

Transpiling to ES5 (—target es5)

  1. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  2. return new (P || (P = Promise))(function (resolve, reject) {
  3. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  6. step((generator = generator.apply(thisArg, _arguments || [])).next());
  7. });
  8. };
  9. var __generator = (this && this.__generator) || function (thisArg, body) {
  10. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  11. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  12. function verb(n) { return function (v) { return step([n, v]); }; }
  13. function step(op) {
  14. if (f) throw new TypeError("Generator is already executing.");
  15. while (_) try {
  16. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  17. if (y = 0, t) op = [0, t.value];
  18. switch (op[0]) {
  19. case 0: case 1: t = op; break;
  20. case 4: _.label++; return { value: op[1], done: false };
  21. case 5: _.label++; y = op[1]; op = [0]; continue;
  22. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  23. default:
  24. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  25. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  26. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  27. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  28. if (t[2]) _.ops.pop();
  29. _.trys.pop(); continue;
  30. }
  31. op = body.call(thisArg, _);
  32. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  33. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  34. }
  35. };
  36. function delay(milliseconds, count) {
  37. return new Promise(function (resolve) {
  38. setTimeout(function () {
  39. resolve(count);
  40. }, milliseconds);
  41. });
  42. }
  43. // async function always returns a Promise
  44. function dramaticWelcome() {
  45. return __awaiter(this, void 0, void 0, function () {
  46. var i, count;
  47. return __generator(this, function (_a) {
  48. switch (_a.label) {
  49. case 0:
  50. console.log("Hello");
  51. i = 0;
  52. _a.label = 1;
  53. case 1:
  54. if (!(i < 5)) return [3 /*break*/, 4];
  55. return [4 /*yield*/, delay(500, i)];
  56. case 2:
  57. count = _a.sent();
  58. console.log(count);
  59. _a.label = 3;
  60. case 3:
  61. i++;
  62. return [3 /*break*/, 1];
  63. case 4:
  64. console.log("World!");
  65. return [2 /*return*/];
  66. }
  67. });
  68. });
  69. }
  70. dramaticWelcome();

You can see full example here.

Note: for both target scenarios, we need to make sure our run-time has an ECMAScript-compliant Promise available globally. That might involve grabbing a polyfill for Promise. We also need to make sure that TypeScript knows Promise exists by setting your lib flag to something like “dom”, “es2015” or “dom”, “es2015.promise”, “es5”.
We can see what browsers DO have Promise support (native and polyfilled) here.