Suraj Pheudin

JavaScript Promise

Sunday, January 22, 2023

blog theme

Overview

Producing Code

Create a Promise To create a promise object, we use Promise() constructor.

let promise = new Promise(function (resolve, reject) {
  // do something
});

The function passed to new Promise is called the executor. The executor receives two arguments: resolve and reject. These functions are pre-defined by the JavaScript engine, so we don't need to create them. We should only call one of them when ready. resolve and reject functions take no or only one argument of any data type.

  • resolve()
  • resolve(data)
  • reject()
  • reject(error)

Calling resolve and reject function

The general idea is, we do something inside executor function which can take any number of seconds to execute. After that we have to call either resolve or reject function.

Some of the common cases are:

  • Call resolve function when code is executed successfully and call reject function when code failed to execute properly.

  • Let's say code executed successfully, but we can still apply conditions according to our need.

  • Call resolve function if we get what we wanted after successful execution.

  • Call reject function if we don't get what we wanted after successful execution.

The freedom is yours, you can call resolve and reject based on your own custom conditions.

Example 1

Based on success of execution of code

function addToLocalStorage(key, value){
	return new Promise(function(resolve, reject){
		try{
			localStorage.setItem(key, value);
			resolve("Successfully added to local storage.");
		}catch(error){
			reject(error);
		}
	}
}

Example 2

Condition according to our need after successful execution

const vote = [];

function addVote(name, birthYear){
	return new Promise(function(resolve, reject){
		const age = 2022 - birthYear;

		// Code is being successfully executed but we apply our own conditions.
		if(age < 18){
			reject(new Error("Not eligible"));
		}else{
			vote.push(name);
			resolve("Vote added successfully.");
		}

	}
}

Consuming Code