Computer >> Computer tutorials >  >> Programming >> Javascript

Async/Await Functions in JavaScript


The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Async await function and operators work on promises.

Async/await functions help us to write completely synchronous-looking code while performing async tasks behind the scenes.

For example, let us say we have a asynchronous function that returns a promise −

// Promise that resolves to 100 after 2sec
function getHundred() {
   return new Promise(resolve => {
      setTimeout(() => {
         resolve(100);
      },    2000);
   });
}

We want to use this in a function, but we need to wait for the return value. Using callbacks we can do this in the following way −

function useGetHundred() {
   getHundred().then((value) => {
      console.log(value);
   })
}

But we need to unnecessarily need to create a callback to execute on the returned data. We can instead use async await to simplify this code −

Example

// Declare an async function. When this function is called, it'll also return a Promise
// But inside this function any async calls can be made synchronous using await keyword
async function useGetHundredAsync() {
   // wait for the getHundred promise to resolve then store its value in value.
   let value = await getHundred();
   console.log(value)
}

Output

100