Skip to content

Instantly share code, notes, and snippets.

@ivanbatic
Last active January 12, 2021 21:55
Show Gist options
  • Save ivanbatic/54d2bfbf2f74109baf56 to your computer and use it in GitHub Desktop.
Save ivanbatic/54d2bfbf2f74109baf56 to your computer and use it in GitHub Desktop.
Typescript async/await demo
"use strict";
class Cheese {
private state = "hard";
public async melt() {
console.log("Melting...");
return new Promise((resolve) => {
setTimeout(() => {
this.state = "melted";
resolve();
}, 2000);
});
}
}
class Dough {
private state = "raw";
public async bake() {
console.log("Baking...");
return new Promise((resolve) => {
setTimeout(() => {
this.state = "baked";
resolve();
}, 3000);
});
}
}
class Pizza {
private dough: Dough;
private cheese: Cheese;
constructor(cheese: Cheese, dough: Dough) {
this.dough = dough;
this.cheese = cheese;
}
public static async create(cheese: Cheese, dough: Dough): Promise<Pizza> {
await Promise.all([cheese.melt(), dough.bake()]);
return new Pizza(cheese, dough);
}
}
(async function () {
let cheese = new Cheese();
let dough = new Dough();
let pizza = await Pizza.create(cheese, dough);
console.log(pizza);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment