Asynchronous Functions

Also known as Async Await
Added in ES 2017.


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 )


Async Patterns

JavaScript is single threaded.
Synchronous program flow is one statement at a time and statements are executed in order. This has blocking.


What we are trying to achieve is to have code that looks synchronous (but is actually running asynchronous code)



Asynchronous Program Flow

Asynchronous program flow means that more than one statement can be executed simultaneously. This is non-blocking
JavaScript has a number of built-in functions that are executed asynchronously by default

setTimeout 
XMLHttpRequest method
requestAnimationFrame


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