15. Asynchronous Tasks
Activity 15.01: Refactoring Promise Code to await/async Syntax
Solution
Here's one implementation of equivalent code that uses async/await
:
- Define the promise variables as follows:
(async () => {Â Â Â Â Â Â let p1 = use1();Â Â Â Â Â let p2 = use2();Â Â Â Â Â let p3 = use3();Â
- It would not have been correct to place the
await
keyword in the initial block when calling each function like this:Â Â Â Â let p1 = await use1(); Â Â Â Â let p2 = await use2(); Â Â Â Â let p3 = await use3();
This is because each of the use cases has a different timeout defined. If you used
await
when callinguse1()
, it would have caused a delay of 3 seconds until it completed beforeuse2()
was even initiated, which is not what you want. Rather, our desire is for all three use cases to trigger one right after the other with no delay, so they execute...