Understanding JavaScript Promises and Async/Await…30daysofJavaScript ==> Day 16

Olajide Blessing Niniola
3 min readJun 29, 2021

Promising result

JavaScript Promises

Ok, let’s keep it simple, JavaScript Promises is a block of code that runs or promises a result. JavaScript promise object may consist of two kinds of codes namely: producing code and consuming code. The producing code is known to run over a period of time before giving the desired result, for instance, a page that loads over the network while the consuming code, on the other hand, waits for the result.

Let us look at a real-life scenario, when you walk into a restaurant, you have a waiter who takes your order and promises to return your food within a period of time depending on how long it takes to prepare it. The waiter here is seen as the producing code while you the customer is the consuming code, the waiter (the producing code)takes his time to give the desired result while you the customer (consuming code)has to wait for the result.

Putting the above together, we can say JavaScript promises link both the producing code and the consuming code together.

JavaScript Promise Object

JavaScript Promise Object is a block of code containing the producing code which calls for the consuming code and below is the syntax. Promise.then() takes two arguments, a callback for success and another for failure. Both are optional, so you can add a callback for success or failure only.

Promise Object Properties

A JavaScript Promise object can be:

  • Pending
  • Fulfilled
  • Rejected

The Promise object supports two properties: state and result. A promise object could be pending(work in progress) if the result is undefined, fulfilled if the result is a value or rejected if the result is an error object. The promise object also has two internal properties namely: State and Result.

A simple example of promise

We can demonstrate further examples using setTimeOut() from our previous episode. See this example in the code snippet below:

set timeout

JavaScript Async and Await

Async and Await are blocks of codes that make it easier to write JavaScript promises. Async makes a function return a Promise while await makes a function wait for a Promise.

Syntaxes

  • Async
async syntax
Async syntax
  • Await

let value = await promise;

The await keyword can only be used inside an async function. It can be used for common functions such as time out and await files. Check here for examples.

What is this about?

30daysofjavascript is a series of writing on how I learn to code in JavaScript. These episodes are as simplified as possible and for beginners like me, I hope you find JavaScript less confusing throughout this episode. Thank you as always and see you in the next episode. Check out every episode I have written here.

Sign up to discover human stories that deepen your understanding of the world.

No responses yet

Write a response