Google News
logo
Ionic - Interview Questions
Explain async and await.
The async and await both are new keyword introduced in the ES2017 to write async functions. They are used to execute asynchronous code blocks. Basically, it allows you to write promises in a more readable way. Let us understand it with the following example.
promiseFunction(){  
    return new Promise((resolve,reject)=>{  
      setTimeout(()=>{  
        resolve("Promises Resolved");  
      },3000);  
    })  
  }​
  
The above function will return a promise, which will be resolved in 3000 milliseconds. We can call the above promise function as below.
promiseFunCall() {  
    this.promiseFunction().then(  
      successData => {  
        console.log(output: successData);  
      },  
      rejectData => {  
        console.log(output: rejectData);  
      }  
    );  
  } ​
 
Now, we are going to see how promises will be converted into the async-await function. The promiseFunction() will remain the same, and the async-await function handled how the promises will be called. So, the above function promiseFunCall() can be re-written as :
async promiseFunCall() {  
    try {  
      let successData= await this.promiseFun();  
      console.log(output: successData);  
    } catch (error) {  
      console.log(error);  
    }  
  } ​
 
Advertisement