Cheatsheets / Learn Asynchronous JavaScript
Promises
States of a JavaScript Promise
A JavaScript Promise object can be in one of three
states: pending , resolved , or rejected . const promise = new Promise((resolve, reject)
While the value is not yet available, the Promise stays in => {
the pending state. Afterwards, it transitions to one of the const res = true;
two states: resolved or rejected . // An asynchronous operation.
A resolved promise stands for a successful completion.
if (res) {
Due to errors, the promise may go in the rejected state.
resolve('Resolved!');
In the given code block, if the Promise is on resolved
state, the first parameter holding a callback function of
}
the then() method will print the resolved value. else {
Otherwise, an alert will be shown. reject(Error('Error'));
}
});
promise.then((res) => console.log(res), (err)
=> alert(err));
The .catch() method for handling rejection
The function passed as the second argument to a
.then() method of a promise object is used when the const promise = new Promise((resolve, reject)
promise is rejected. An alternative to this approach is to => {
use the JavaScript .catch() method of the promise setTimeout(() => {
object. The information for the rejection is available to reject(Error('Promise Rejected
the handler supplied in the .catch() method.
Unconditionally.'));
}, 1000);
});
promise.then((res) => {
console.log(value);
});
promise.catch((err) => {
alert(err);
});
JavaScript Promise.all()
The JavaScript Promise.all() method can be used to
execute multiple promises in parallel. The function const promise1 = new Promise((resolve, reject)
accepts an array of promises as an argument. If all of the => {
promises in the argument are resolved, the promise setTimeout(() => {
returned from Promise.all() will resolve to an array
resolve(3);
containing the resolved values of all the promises in the
}, 300);
order of the initial array. Any rejection from the list of
});
promises will cause the greater promise to be rejected.
const promise2 = new Promise((resolve, reject)
In the code block, 3 and 2 will be printed respectively
even though promise1 will be resolved after promise2 . => {
setTimeout(() => {
resolve(2);
}, 200);
});
Promise.all([promise1, promise2]).then((res)
=> {
console.log(res[0]);
console.log(res[1]);
});
Executor function of JavaScript Promise object
A JavaScript promise’s executor function takes two
functions as its arguments. The first parameter represents const executorFn = (resolve, reject) => {
the function that should be called to resolve the promise resolve('Resolved!');
and the other one is used when the promise should be };
rejected. A Promise object may use any one or both of
them inside its executor function.
const promise = new Promise(executorFn);
In the given example, the promise is always resolved
unconditionally by the resolve function. The reject
function could be used for a rejection.
.then() method of a JavaScript Promise object
The .then() method of a JavaScript Promise object can
be used to get the eventual result (or error) of the const promise = new Promise((resolve, reject)
asynchronous operation. => {
.then() accepts two function arguments. The first setTimeout(() => {
handler supplied to it will be called if the promise is resolve('Result');
resolved. The second one will be called if the promise is
}, 200);
rejected.
});
promise.then((res) => {
console.log(res);
}, (err) => {
alert(err);
});
setTimeout()
setTimeout() is an asynchronous JavaScript function that
executes a code block or evaluates an expression through const loginAlert = () =>{
a callback function after a delay set in milliseconds. alert('Login');
};
setTimeout(loginAlert, 6000);
Avoiding nested Promise and .then()
In JavaScript, when performing multiple asynchronous
operations in a sequence, promises should be composed const promise = new Promise((resolve, reject)
by chaining multiple .then() methods. This is better => {
practice than nesting. setTimeout(() => {
Chaining helps streamline the development process resolve('*');
because it makes the code more readable and easier to
}, 1000);
debug.
});
const twoStars = (star) => {
return (star + star);
};
const oneDot = (star) => {
return (star + '.');
};
const print = (val) => {
console.log(val);
};
// Chaining them all together
promise.then(twoStars).then(oneDot).then(print
);
Creating a Javascript Promise object
An instance of a JavaScript Promise object is created
using the new keyword. const executorFn = (resolve, reject) => {
The constructor of the Promise object takes a function, console.log('The executor function of the
known as the executor function, as the argument. This promise!');
function is responsible for resolving or rejecting the };
promise.
const promise = new Promise(executorFn);
JavaScript Promise Object
A JavaScript Promise is an object that can be used to get
the outcome of an asynchronous operation when that
result is not instantly available.
Since JavaScript code runs in a non-blocking manner,
promises become essential when we have to wait for
some asynchronous operation without holding back the
execution of the rest of the code.
Chaining multiple .then() methods
The .then() method returns a Promise, even if one or
both of the handler functions are absent. Because of this, const promise = new Promise(resolve =>
multiple .then() methods can be chained together. This setTimeout(() => resolve('dAlan'), 100));
is known as composition.
In the code block, a couple of .then() methods are promise.then(res => {
chained together. Each method deals with the resolved
return res === 'Alan' ? Promise.resolve('Hey
value of their respective promises.
Alan!') : Promise.reject('Who are you?')
}).then((res) => {
console.log(res)
}, (err) => {
alert(err)
});