Async JS in a nutshell - final

Async JS in a nutshell - final

Async / await for one last time.

Hey folks, I want to finish this puzzle once in for all. The async/ await is a very very very useful piece to make peace with JS.

Pre-req: Async JS, CallBack, CallBack hell, and finally Promises and Promise chaining. Well, I think I will go over it again.

Promise Chaining

Well, the regime is all about fetching some data from backend APIs some databases, or whatever XYZ. To achieve this there are many steps and one such is Promise chaining(dizzy one). It is a phenomenon where you use .then().then() and go on.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

  alert(result); // 1
  return result * 2;

}).then(function(result) { // (***)

  alert(result); // 2
  return result * 2;

}).then(function(result) {

  alert(result); // 4
  return result * 2;

});

See the .then() very traumatic, let me explain what happens.

Here the flow is:

  1. The initial promise resolves in 1 second (*),

  2. Then the .then handler is called (**), which in turn creates a new promise (resolved with 2 value).

  3. The next then (***) gets the result of the previous one, processes it (doubles), and passes it to the next handler.

  4. …and so on.

See, this is it. Well, many of the developers still find it nice and handy but there is an awesome workaround for the same. Yes, you guessed it right.

Async / Await

Let us ask Mr. Wikipedia...

In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function.

Hmm... well, it is complex, but let me simplify this for you. Simply put it is a non-blocking paradigm or block of code, that is asynchronous as a whole but with synchronous behavior internally until it resolves a promise.

Syntax:

async function f() {
  return something;//anything
}

async means that this will return a promise. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.

//Async Await
console.log("one")
const getData = async () => {
  const responseOne = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const dataOne = await responseOne.json();
  const resp2 = await fetch("https://jsonplaceholder.typicode.com/todos/2");
  const dataTwo = await resp2.json();
  const resp3 = await fetch("https://jsonplaceholder.typicode.com/todos/3");
  const dataThree = await resp3.json();

  return { dataOne, dataThree, dataTwo };
};
//since sync it is non blocking and returns a promise
getData()
  .then((data) => {
    const { dataOne, dataTwo, dataThree } = data;
    console.log(dataOne, dataTwo, dataThree);
  })
  .catch((err) => {
    console.log(err.message);
  });
console.log("two")

Try to understand this block, it is a simple function:

  1. Print "one"

  2. getData() an async function is called and it is 'offloaded' remember I said "it starts now and finishes sometime later", so the process happens completely offload in a different part of the browser. Now, await fetch("some parameter is executed"), this one returns something and then only the next line inside the getData function executes and this is just like saying. first line.then() the next line. So all the lines do the same thing only the variables I fixed are different. Simple and then it returns a value.

  3. Print "two", why? because async is asynchronous and returns a promise.

Isn't it simple? Async/await is simply a paradigm that can replace.then() chaining(the promise chaining) to improve readability of the function. Yes, it might be difficult and a bit overwhelming at the beginning this will be on track. Trust me!.

I hope you enjoyed this series. Thanks for the overwhelming love. I will see you on the next one.