The async keyword

First, we have the async keyword, which you put in front of a function declaration to turn it into an asynchronous function.

An asynchronous function is a function that will react to a possible use of the await keyword to invoke asynchronous code.

Let us turn one function into an asynchronous function :

async function hello() { return "Bonjour" };
hello();

//or
let hello = async function() { return "Bonjour" };
hello();

//or
let hello = async () => { return "Bonjour" };
hello();

Invoking the function now returns a promise. This is one of the characteristics of asynchronous functions – their return values ??are necessarily converted to promises.

To actually consume the returned value when the promise is fulfilled, since it returns a promise, we could use a .then () block:

hello().then((value) => console.log(value));

Thus, the async keyword is added to functions to tell them to return a promise rather than directly returning the value.

The await keyword

The advantage of an asynchronous function only becomes apparent when you combine it with the await keyword. await only works inside asynchronous functions in regular JavaScript code, but it can be used on its own with JavaScript modules.

await can be placed in front of any asynchronous function based on a promise to pause your code on that line until the promise is fulfilled, then return the resulting value.

async function hello() {
  return salutation = await Promise.resolve("Bonjour");
};

hello().then(console.log);

The example above is not very useful, although it serves to illustrate the syntax.

Following, ein better explained example:

async function myFetch() {
  let response = await fetch('coffee.jpg');
  if (!response.ok) {
    throw new Error(`Erreur HTTP ! statut : ${response.status}`);
  }
  return await response.blob();

}

myFetch().then((blob) => {
  let objectURL = URL.createObjectURL(blob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}).catch(e => console.log(e));

But how does it work?

the .catch () block will catch errors occurring both in the asynchronous function call and in the chain of promises.

Let´s notice that we’ve wrapped the code inside a function, and we’ve included the async keyword before the function keyword. This is necessary – we need to create an async function to define a block of code in which we will run our async code; as we said before, await only works inside async functions.

Inside the definition of the myFetch () function, instead of having to chain a .then () block at the end of each promise-based method, we just add an await keyword before the method call, then assign the result to a variable.

The await keyword causes the JavaScript runtime to pause our code on this line, not allowing other code to execute in the meantime until the asynchronous function call returned its result – very useful if the following code depends on this result!

Once that’s done, our code continues to run from the next line. For example :

let response = await fetch('coffee.jpg');

The response returned by the filled fetch () promise is assigned to the response variable when that response becomes available, and the parser pauses on that line until that happens. Once the answer is available, the parser moves to the next line, which creates a blob from it. This line also invokes a promise-based async method, so we’re using await here as well. When the result of the operation comes back, we return it out of the myFetch () function.

This means that when we call the myFetch () function, it returns a promise, so that we can chain a .then () at the end of it inside which we manage the display of the blob to the screen.

Reference:

https://developer.mozilla.org/

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *