Async/Await with easy to understand examples.

 
Let's first understand the Async keyword.
Put this keyword before the function which returns a promise or which does an asynchronous task.
const foo = async () => {
  return 'done';
}
foo().then((res) => console.log(res));
// done
If you think your function will run asynchronously (fetching data from API) then use the async keyword before that function.
Now there is another keyword Await that works only inside async functions.
(There is a concept of top-level await in which await keyword can be used outside of the async function.)
The Await keyword simply means it makes JavaScript wait until the task is completed.
const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('done');
    }, 1000);
  });
}
const foo = async () => {
  const res = await asyncTask();
  console.log(res);
}
console.log('Before Foo Call');
foo();
console.log('After Foo Call');
In the above example, I am creating a dummy function that takes one second to return its result.
There is another function foo that calls asyncTask (with await keyword) and prints the result.
I have put two logs, one is before calling foo and the second is after calling foo.
What do you think will be the output? 🤔
As you may know, whenever JavaScript encounter with await keyword it stops the execution of the current function and put it into the callback queue and start executing the next statement which is the second console log.
Here is an output of the above code.
Before Foo Call
After Foo Call
done
Handling errors while using async/await
In the above example, our promise resolves normally and we are printing the result on the console.
But in case of rejection, it will throw an error so we should handle errors while working with promises.
Using try/catch block.
const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('Something not working!');
    }, 1000);
  });
}
const foo = async () => {
  try {
    const res = await asyncTask();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
  console.log('After calling AsyncTask');
}
foo();
Now, If our asyncTask function throws an error control will go into catch block and simply prints the error message then it will start to execute the next statements.
Output
Something not working!
After calling AsyncTask
Very clean. Isn't it?
Now, try to use async/await instead of then/catch in your next project.

#viastudy

Post a Comment

0 Comments