InterviewSolution
Saved Bookmarks
| 1. |
What is async and await explain it with a code snippet. |
|
Answer» Async and await are used to execute asynchronous code BLOCKS. The main reason they are used is to increase the readability of the code. a. Say there are 2 network calls that need to be done one after the other, we can achieve it using async and await with below code snippet. i. async addWithAsync() { const result1 = <NUMBER>await this.networkCallOne(20); const result2 = <number>await this.networkCallTwo(30); this.additionAsyncResult = result1 + result2; console.log(`async result: ${this.additionAsyncResult}`); }ii. In the above code, until first line EXECUTES control will not come to second line. If we try to achieve the same promises or observable, we need to write code, as mentioned below. iii. addWithPromise() { this.networkCallOne(20).then(data1 => { let result1 = <number>data1; this.networkCallTwo(30).then(data2 => { let result2 = <number>data2; this.additionPromiseResult = result1 + result2; console.log(`promise result: ${this.additionPromiseResult}`); }); });iv. With above code pattern when HIERARCHY increases, the readability of the code decreases. |
|