JavaScript Promises
Posted on September 26, 2020 in JavaScript by Matt Jennings
Definition
A Promise is a special JavaScript object that represents an eventual result of an asynchronous action.
A Promise has two properties:
- Promise status.
- Promise value.
States of the Promise
A promise can be in 1 of 3 states:
- Pending (value property is undefined).
- Fulfilled (value property is assigned to something).
- Rejected (will contain a reason why the promise has failed in the value property).
How to Use Promises using the then
Method
then
method takes 2 arguments:
- On fulfilled.
- On rejected.
Simple example promise using setTimeout()
:
/* 1. calculateSquare function with using the instantiated Promise constructor function that takes in a single function parameter that itself has parameters of resolve and reject which are both functions. 2. The function passed into the Promise constructor function as a parameter can inside asynchronous functions inside it, like setTimeout() 3. Finally the promise object is returned that is assigned to the Promise function constructor with parameters passed into the resolve and reject methods. */ function calculateSquare(number) { const promise = new Promise(function(resolve, reject) { setTimeout(function() { if(typeof number !== 'number') { return reject(new Error('Argument of type number is expected')); } const result = number * number; return resolve(result); }) }, 1000); return promise; } /* To get the resolve and reject values: 1. Call the function with a parameter passed in and then call the .then method (which you can do because a promise object is returned from the function declaration above). 2. Inside the .then method pass in 2 parameters, a resolve anonymous function with a parameter like "success" that includes a success message inside it and a reject anonymous function with a parameter like "fail" that incluees a failur message inside it. */ // Output below is: // "Success: 16" calculateSquare(4) .then(success => { console.log('Success: ' + success); }, fail => { console.log(fail.toString()); } ); // Output below is: // "Error: Argument of type number is expected" calculateSquare('blah') .then(success => { console.log('Success: ' + success); }, fail => { console.log(fail.toString()); } );
Example of turning a regular function into a promise:
function capitalizeFirstLetter(text) { return new Promise(function(resolve, reject) { if(typeof text !== 'string') { return reject(new Error('Argument must be a string')); } const result = text[0].toUpperCase() + text.slice(1, text.length); return resolve(result); }); } // Output: // "Too black, too strong" capitalizeFirstLetter('Too black, too strong') .then(function(success) { console.log('Too black, too strong'); }, function(fail) { console.log(fail); } ); // Output: // "Error: Argument must be a string" capitalizeFirstLetter(6) .then(function(success) { console.log('Too black, too strong'); }, function(fail) { console.log(fail.toString()); } ); // Another error example with a catch method // and the output is: // "Error: Argument must be a string" capitalizeFirstLetter(6) .then(function(success) { console.log('blah'); }) .catch(function(fail) { console.log(fail.toString()); });