JavaScript: Asynchronous Operations

#BuildTogether Day96/100

An Asynchronous operation is one that allows the computer to “move on” to other tasks while waiting for the asynchronous operation to complete. Asynchronous programming means that time-consuming operations don’t have to bring everything else in our programs to a halt.

Operations like making a network request or querying a database can be time-consuming, but JavaScript allows us to execute other tasks while awaiting their completion.

What is a Promise?

Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states:

  • Pending: The initial state — the operation has not been completed yet.
  • Fulfilled: The operation has been completed successfully and the promise now has a resolved value. For example, a request’s promise might resolve with a JSON object as its value.
  • Rejected: The operation has failed and the promise has a reason for the failure. This reason is usually an Error of some kind.

All promises eventually settle, enabling to write the logic for what to do if the promise fulfills or if it rejects.

Constructing a Promise Object

To create a new Promise object, use the new keyword and the Promise constructor method:

const executorFunction = (resolve, reject) => { };
const myFirstPromise = new Promise(executorFunction);

The Promise constructor method takes a function parameter called the executor function which runs automatically when the constructor is called. The executor function starts an asynchronous operation and dictates how the promise should be settled.

The executor function has two function parameters, referred to as the resolve() and reject() functions. The resolve() and reject() functions aren’t defined by the programmer. When the Promise constructor runs, JavaScript will pass its own resolve() and reject() functions into the executor function.

  • resolve is a function with one argument. Under the hood, if invoked, resolve() will change the promise’s status from pending to fulfilled, and the promise’s resolved value will be set to the argument passed into resolve().
  • reject is a function that takes a reason or error as an argument. Under the hood, if invoked, reject() will change the promise’s status from pending to rejected, and the promise’s rejection reason will be set to the argument passed into reject().

An example executor function in a Promise constructor:

const executorFunction = (resolve, reject) => {
if (someCondition) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
}
const myFirstPromise = new Promise(executorFunction);

Let’s break down what’s happening above:

  • A variable myFirstPromise is declared.
  • myFirstPromise is constructed using new Promise() which is the Promise constructor method.
  • executorFunction() is passed to the constructor and has two functions as parameters: resolve and reject.
  • If someCondition evaluates to true, invoke resolve() with the string 'I resolved!'
  • If not, we invoke reject() with the string 'I rejected!'

In this example, myFirstPromise resolves or rejects based on a simple condition, but, in practice, promises settle based on the results of asynchronous operations. For example, a database request may fulfill with the data from a query or reject with an error thrown.

An example exercise of having a promise

If you fancy checking my 100DaysOfCode, please feel free to drop by

--

--

--

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, Kotlin and paper crafts.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Unsubscribing From All YouTube Channels In One Go

For now, JavaScript has a numbers advantage: 68% of developers use JavaScript, compared to 44% who

Introduction to Redux with a simple react-redux example

How to install Angular CLI?

How we create a reusable CTA button with React Hook in Next.js

Next.js + Typescript + GraphQL + MongoDB = ❤️

Sending Files Directly From Client to Amazon S3 — Signed URLs

Frequently asked: React JS Interview Questions and Answers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Henna Singh

Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, Kotlin and paper crafts.

More from Medium

Uses of JavaScript and MongoDB

JavaScript objects in depth.

More About JavaScript, Version Controlling, NoSQL

Scope in JavaScript