DEV Community

Cover image for Easy Callback, Promises, Async-Await
Prakhar Yadav
Prakhar Yadav

Posted on

Easy Callback, Promises, Async-Await

After having read about callbacks, promises & async-await multiple times in not so easy to comprehensions, I finally have wrapped my head around them.
And today I'd share it in simpler terms that I am able to remember & understand.


Callbacks

Call me back post-it note

Callbacks are functions being passed as arguments. That's it. That doesn't satisfy you then read these one page articles (to arrive on same conclusion of course):


Promises:

Promise resolve & reject

functions that are not run sequentially. They are run when possible.

const fun = new Promise ((resolve, reject) => {
  if(<some condition>)
    resolve("some success message");
  else
    reject("some failure message");
});


fun()
  .then(msg => console.log(msg)) // some success message
  .catch(msg => console.log(msg)); // some failure message
Enter fullscreen mode Exit fullscreen mode

Resolve is called to indicate & return success status of the Promise, & Reject is called when we need to show failure.

Once returned we need to handle the stuff as well right?

  • then() is used to handle the resolved state
  • catch() is used to handle the rejected state

See! Simple.

Detailed flow diagram of how a Promise works


Async - Await

async await code poster

Just a wrapper around Promise. Async-Await use Promises in the background.
Why was this done?
Because sometimes developers tend to nest things up. Nesting Promises makes it difficult to write, read, follow & understand at one look.

So why not make it easy to read & understand.

const fun = async () => {
  await functionToPerformAsynchronously();
}
Enter fullscreen mode Exit fullscreen mode

That easy. You can easily make any function run asynchronously, by appending a await before it. Just remember that await statement must be in a function declared as async.

And you know what! async functions are nothing but promises (well not really; they return promises).

Don't confuse yourself, just read along and find more detail in the links mentioned at the end.

Which is why you can do this:

const fun = async () => {
  await functionToPerformAsynchronously();
}

fun()
  .then(<whatever you want to do here>) //runs when fun() has run successfully and did not encounter any issue while it ran
  .catch(errorMsg => console.log(errorMsg)); // runs when fun() had some problem running. We can display the problem as an error message is returned & can be displayed like in this example.
Enter fullscreen mode Exit fullscreen mode

Want to know more

Want to dig deeper?

Here are one of the best & easy to follow official Node documentation on each one of the three:

Discussion (0)