Async/Await with simple to grasp examples.




Let’s first perceive the Async key phrase.

Put this key phrase earlier than the operate which returns a promise or which does an asynchronous job.

const foo = async () => {
  return 'accomplished';
}

foo().then((res) => console.log(res));

// accomplished
Enter fullscreen mode

Exit fullscreen mode

In case you suppose your operate will run asynchronously (fetching information from API) then use the async key phrase earlier than that operate.

Now there may be one other key phrase Await that works solely inside async features.

(There’s a idea of top-level await during which await key phrase can be utilized exterior of the async operate.)

The Await key phrase merely means it makes JavaScript wait till the duty is accomplished.

const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('accomplished');
    }, 1000);
  });
}

const foo = async () => {
  const res = await asyncTask();
  console.log(res);
}

console.log('Earlier than Foo Name');
foo();
console.log('After Foo Name');
Enter fullscreen mode

Exit fullscreen mode

Within the above instance, I’m making a dummy operate that takes one second to return its end result.

There may be one other operate foo that calls asyncTask (with await key phrase) and prints the end result.

I’ve put two logs, one is earlier than calling foo and the second is after calling foo.

What do you suppose would be the output? πŸ€”

As you could know, each time JavaScript encounter with await key phrase it stops the execution of the present operate and put it into the callback queue and begin executing the following assertion which is the second console log.

Right here is an output of the above code.

Earlier than Foo Name
After Foo Name
accomplished
Enter fullscreen mode

Exit fullscreen mode



Dealing with errors whereas utilizing async/await

Within the above instance, our promise resolves usually and we’re printing the end result on the console.

However in case of rejection, it should throw an error so we must always deal with errors whereas working with guarantees.

Utilizing attempt/catch block.

const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('One thing not working!');
    }, 1000);
  });
}

const foo = async () => {
  attempt {
    const res = await asyncTask();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
  console.log('After calling AsyncTask');
}

foo();
Enter fullscreen mode

Exit fullscreen mode

Now, If our asyncTask operate throws an error management will go into catch block and easily prints the error message then it should begin to execute the following statements.

Output

One thing not working!
After calling AsyncTask
Enter fullscreen mode

Exit fullscreen mode

Very clear. Is not it?

Now, attempt to use async/await as an alternative of then/catch in your subsequent venture.

In case you like this text like, share and mark πŸ”– this text!

πŸƒβ€β™‚οΈ You possibly can observe me on πŸ‘‡

πŸ•Š Twitter : https://twitter.com/nehal_mahida

πŸ‘¨β€πŸ’» Github: https://github.com/NehalMahida





Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#AsyncAwait #simple #perceive #examples