1.

Explain async and await in JavaScript.

Answer»

Async/Await is a SPECIAL SYNTAX that allows developers to work with JavaScript promises in an easier and more comfortable manner.

Async is a keyword that is written before a function definition, which indicates that the function always returns a promise.

Await is a keyword that is used inside a function marked async. You cannot use await in a not async function. The await keyword makes JavaScript wait until a promise is settled and the result is RETURNED.

Example,

async function fetchData() {           LET promise = new Promise((RESOLVE, reject) => {                     setTimeout(() => { resolve(‘Promise is successful’);}, 2000);           });           let result = await promise;             console.log(result); }

Running the above function will log ‘Promise is successful’ after 2 seconds in the console.  

The function call fetchData() will return a promise which is later resolved to the value ‘Promise is successful’.  

On the line  

let result = await promise;

JavaScript waits for the promise variable to be resolved before the value is returned to the result variable.



Discussion

No Comment Found