How to Use Promises in Javascript!

How to Use Promises in Javascript!

Before creating this, I didn’t imagine there would be so many different ways to create a Promise. I imagine that it’s likely that I may have also missed a few.

Before creating this, I didn’t imagine there would be so many different ways to create a Promise. I imagine that it’s likely that I may have also missed a few.

There’s a lot of redundancy here, but every method is worth going over in detail because of the nuances.

1. Create a new Promise

This is the standard (or typical) way of creating a Promise. It offers the most flexibility, but it’s also the most verbose.

// (1) resolved
new Promise(resolve => {
  resolve(888)
})
// (2) rejected
new Promise((_, reject) => {
  reject(666)
})

This method exposes resolve and reject functions that can be later called when it’s time to resolve the Promise.

new Promise(resolve => {
  setTimeout(() => resolve(888), 1000)
})

2. Static methods

Promise has a pair of static methods, resolve and reject, to quickly create a new Promise with either a resolved or rejected value.

// (3) resolved
Promise.resolve(888)
// (4) rejected
Promise.reject(666)

This is handy when a function needs a Promise as an argument or as a return value.

// example
const fetchJson  = (input) => {
  // always return a Promise
  if (!input) return Promise.reject('input cannot be empty')
  /* more code here */
}

3. Then and Catch

The then method on a resolved Promise will return a new Promise. Likewise, the catch method of a rejected Promise will return a new Promise.

// (5) resolved -> resolved
Promise.resolve().then(() => 888)
// (6) rejected -> rejected
Promise.reject().catch(() => Promise.reject(666))
// (7) rejected -> rejected
Promise.reject().catch(() => {
  throw 666
})

The then method on a rejected Promise and the catch method on a resolved Promise also return a new Promise. But they don’t execute the callbacks and are equivalent to the original Promise.

// (8) stays resolved (888)
Promise.resolve(888).catch(() => 666)
// (9) stays rejected (666)
Promise.reject(666).then(() => 888)

Note: While the value stays the same, the method returns a new Promise (and they are not equal).

// resolved (888)
const p1 = Promise.resolve(888)
// resolved (888)
const p2 = p1.catch(() => {})
p1 == p2 //=> false

4. Resolved <-> Rejected

A rejected Promise doesn’t have to stay rejected, it can return a resolved Promise and vice-versa.

This is handy when a Promise is rejected, but you want to handle the error and return a new value.

Or if the value returned doesn’t pass additional validation, you can force a rejection.

// (10) rejected -> resolved
Promise.reject().catch(() => 888)
// (11) rejected -> resolved
Promise.reject().catch(() => Promise.resolve(888))
// (12) resolved -> rejected
Promise.resolve().then(() => Promise.reject(666))
// (13) resolved -> rejected
Promise.resolve().then(() => {
  throw 666
})

Take note how a value returned from catch will return a resolved Promise. This can be the source of bugs.

5. Async / Await

A function marked with async always returns a Promise.

A returned value will be wrapped in a Promise.

A Promise can also be returned. The value inside will be unwrapped and then rewrapped in a new Promise object.

// (14) function returns resolved (888)
async function func() {
  return 888
}
// (15) arrow returns resolved (888)
const func = async () => {
  return 888
}
// (16) return rejected (666)
const func = async () {
  return Promise.reject(666)
}
// (17) return rejected (666)
const func = async () {
  throw 666
}

6. Thenables

Any object that has a then method can be used in place of a Promise.

// (18) resolved (888)
Promise.resolve({ then: resolve => resolve(888) })
// (19) rejected (666)
Promise.resolve({ then: (_, reject) => reject(666) })
// (20) treated as a Promise, resolves to 888
await {
  then(resolve) {
    resolve(888)
 }
}
// (21) treated as a Promise, resolves to 888
await {
  then(_, reject) {
    reject(666)
 }
}

The use cases for this is pretty limited and usage is not encouraged, but it’s good to know that it is possible. If you know of a valid use case, to use this over a Promise, let me know in the comments.

Fin

The Promise has a lot of flexibility, offering a handful of ways to be created and transformed. Becoming familiar with all of these techniques will help you choose the right tool for the right situation.

javascript programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.

Learning JavaScript: Data Types and Variables

To paraphrase the title of an old computer science textbook, “Algorithms + Data = Programs.” The first step in learning a programming language such as JavaScript is to learn what types of data the language can work with. The second step is to learn how to store that data in variables. In this article I’ll discuss the different types of data you can work with in a JavaScript program and how to create and use variables to store and manipulate that data.

[ Professor JavaScript ]: Introduction

Professor JavaScript is a JavaScript online learning courses YouTube Channel. Students can learn how to develop codes with JavaScript from basic to advanced levels through the online courses in this YouTube channel.

From imperative to declarative JavaScript

In this post, I will explain why declarative code is better than imperative code. Then I will list some techniques to convert imperative JavaScript to a declarative one in common situations.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.