Async Await

Added in ES 2017.
Also known as Async Functions
An async function is a function declared with the async keyword, and the await keyword is permitted within it.
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
Async functions allow you to write promise-based code as if it were synchronous, but without blocking the main thread.
If you use the 'async' keyword before a function definition, you can then use the 'await' within the function.
When you 'await' a promise, the function is paused in a non-blocking way and waits for the promise to complete.
If the promise succeeds then value is returned.
If the promise fails then execution is passed to the catch.

async function myFunction () { 
   try {
      const succeedvalue = await myPromise
   }
   catch (rejectedValue) {
   }
}


Nested Callbacks


function asyncMethod(message, num) { 
  return new Promise( function (succeed, fail) {
    setTimeout( function() {
      console.log(message + ' ' + num);
      suceed(num + 1);
     }, 400)
  });
}

Remove all the functions

async function main() { 
  var one = await asyncMethod('Connect to Database', 0)
  var two = await asyncMethod('Verify User Details', one )
  var three = await asyncMethod('Check Permissions', two )
  var four = await asyncMethod('Update User', three )




© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext