Last active
January 12, 2021 21:55
-
-
Save ivanbatic/54d2bfbf2f74109baf56 to your computer and use it in GitHub Desktop.
Typescript async/await demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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