JavaScript — Promises & Async/Await

Dulya Kemali Perera
3 min readApr 3, 2021

--

When we are dealing with tasks that are written in JavaScript, rely on other tasks to complete the task. It’s a combination of different type of tasks and we are ended up with many nested callback functions that are dependent on the previous callback function. This is often referred to as a callback hell, as we end up with tons of nested callback functions that make the code quite difficult to read!

As a solution we have Promise to help us out!

What’s Promises?

“A promise is a placeholder for a value that can either resolve or reject at some time in the future”

You’ll read something like this in many of tutorials. It seems like a promise we have made for someone to do in future😏!

Promise syntax

We can create a promise, using a Promise constructor that receives callback.

Taken from ⭐️🎀 JavaScript Visualized: Promises & Async/Await — DEV Community 👩‍💻👨‍💻

Your console will output the Promise object that contains a status, [[PromiseStatus]] and a value [[PromiseValue]].

Above example is showing pending and undefined respectively values of [[PromiseStatus]] and [[PromiseValue]].

But you can’t access these properties, so no need to worry about these properties.

Above example just passed the simple callback function () => {} to the Promise constructor. However, this callback function receives two arguments.

Two arguments are:

1. resolve or res — the method to be called when the Promise should resolve.

2. reject or rej — the value method to be called when the Promise should reject / something went wrong.

Let’s try and see that logged when we invoke either the res & rej as an arguments in Promise.

Taken from ⭐️🎀 JavaScript Visualized: Promises & Async/Await — DEV Community 👩‍💻👨‍💻

The status of a Promise is fulfilled if we invoke the resolve method, and the status of the Promise is rejected if we invoked the rejected method.

Async / Await

Introduced a new way to add async behavior in JavaScript and make it working with promises. That means we can create async functions which return a promise.

Taken from ⭐️🎀 JavaScript Visualized: Promises & Async/Await — DEV Community 👩‍💻👨‍💻

Instead of using the Promise object, we can create asynchronous function that return an object.

The power of async functions can be seen when using the await keyword! By using await word we can suspend the asynchronous function while we wait for the awaited value return a resolved promise.

Hmm.. that’s not all about the Promises and Async / Await. There are more than you thought in here. I’m also still learning about this. I will write more details in future about these. However these are basics of Promises and Async/Await.

--

--