13. Async/Await in TypeScript
Activity 13.01: Refactoring Chained Promises to Use await
Solution:
Let's go over what needed to change in order to make this work:
- First of all, the
await
keyword can only be used inside anasync
function, so we must add that keyword to the function declaration:const renderAll = async () => {
- Now we have to replace
then
withawait
. Let's look again at what therender
function does. In our simple case, it just returns a promise that resolves to a string, but in the real world, it would render something in a web browser and then resolve to a string. Since we want to log out that string, we can actually resolve the promise inside aconsole.log
statement. Even thoughconsole.log
is a synchronous operation, puttingawait
inside it will cause the function to print out the resolved promise value, exactly as we would hope.The refactored program is six lines shorter and eliminates nesting:
export class El { constructor...