Javascript - Await and Async Syntax

Javascript - Await and Async Syntax

About

await and async is the second promise syntax that permits to manipulate promise.

The async/await syntax is part of ECMAScript 2017 and reduces the callback nesting find in the chaining syntax.

Example

addOne = async function(x){
   return x+1;
};
// Function declared as async so await can be used
(async () => {
    // A aysnc function call returns a promise
    promise = addOne(0)
    //
    let a;
    try {
       // You unwrapp the promise with the 'await' keyword 
       // You get the value (or an error is thrown)
        a = await promise;
    } catch (e) {
       // You catch the error
       console.log("Error! "+e);
    }
    //
    // Tip And you can have the creation of the promise and the await call on the same line
    a = await addOne(a);
    console.log("The value of a is now "+a);
})();

Concept

async/await is a promises syntax handling where:

  • async returns a promise by declaring a executor function
  • await:
    • unwraps a promise and either:
      • returns the return value the promise was resolved with
      • or throws an error if the promise was rejected.
    • should be used within an async function (Chrome now seems to support top level await)
  • error handling is done with try/catch block (promise chaining has a catch function)

The async / await syntax reduce the callback nesting.

Management

Promise creation

The return value of an async function is always a promise.

async function fn(x){
   if (x) {
     throw new Error("Error !");
   } else {
      return "All good";
   }
};

// The return value of an ''async'' function is always a promise. 
v = fn();
console.log("We go back a "+v.constructor);

Fulfillment

Get the resolved value

addOne = async function(x){
   return x + 1;
};

(async () => {
	const a = await addOne(0);
	console.log("The value after await is "+a);
})();

Failure

With a try/catch block.

failBad = async function(){
   throw new Error("Bad failure")
};

(async () => {
    try {
	const a = await failBad(0);
	console.log("The value after await is "+a);
   } catch (e) {
       console.log("Failure !!! with the message ("+e.message+")");
   }
})();

Example

Async fetching

One

// This function returns a fetch that returns a promise
// Don't return any other type of value otherwise the wait will have no effect
function wait(sec,name) {
   if (typeof sec === undefined){
      sec = 1;
   }
   if (typeof name === undefined){
      name = 'Default Promise Name';
   }
   log(name+": Waiting "+sec+" seconds");

   return fetch("https://gerardnico.com/wait.php?sleep="+sec)
   .then(function(response) {
        status = response.status;
        log(name+": has waited "+sec+" seconds and returned (Statuscode: "+response.status+")");
        return status;
    })

}

function log(txt){
   now = new Date(Date.now());
   console.log(now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+" - "+txt);
}
( async () => {
    log("Main: Creating promises");
    promise = wait(5, "Promise");
    log("Main: Await promise");
    let returnValue = await promise;
    log("Main: We got a return value ("+returnValue+")");
}
)();

Many

Async fetching

// This function returns a fetch that returns a promise
// Don't return any other type of value otherwise the wait will have no effect
function wait(sec,name) {
   if (typeof sec === undefined){
      sec = 1;
   }
   if (typeof name === undefined){
      name = 'Default Promise Name';
   }
   log(name+": Waiting "+sec+" seconds");

   return fetch("https://gerardnico.com/wait.php?sleep="+sec)
   .then(function(response) {
        status = response.status;
        log(name+": has waited "+sec+" seconds and returned (Statuscode: "+response.status+")");
        return status;
    })

}

function log(txt){
   now = new Date(Date.now());
   console.log(now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+" - "+txt);
}

log("Main: Creating promises");
let promises = [];
promises.push(wait(1, "Promise 1"));
promises.push(wait(5, "Promise 5"));
log("Main: Promise all promise");

// Promise create another thread and let the script execution continue
Promise
    .all(promises)
    .then(results=> log("PromiseAll: All promises has returned with "+results.length+" results"));
log("Main: End of the script will be fired immediately !");





Discover More
Javascript - Asynchrony

This page is Asynchrony in javascript. Asynchrony is not only critical to the performance of our applications, but it’s also increasingly becoming the critical factor in writability and maintainability....
Javascript Es Promise State
Javascript - Promise Function

in the Javascript context A promise is a function that encapsulate a executor function in order to: execute it asynchronously and returns its result (ie ) A promise is one way of enabling asynchrony...



Share this page:
Follow us:
Task Runner