Learn JavaScript: Asynchronous Actions
Take advantage of one of JavaScript's prominent features: asynchronous actions.
StartKey Concepts
Review core concepts you need to learn to master this subject
States of a JavaScript Promise
Executor function of JavaScript Promise object
.then() method of a JavaScript Promise object
The .catch()
method for handling rejection
JavaScript Promise.all()
Avoiding nested Promise
and .then()
setTimeout()
Creating a Javascript Promise object
States of a JavaScript Promise
States of a JavaScript Promise
const promise = new Promise((resolve, reject) => {
const res = true;
// An asynchronous operation.
if (res) {
resolve('Resolved!');
}
else {
reject(Error('Error'));
}
});
promise.then((res) => console.log(res), (err) => alert(err));
A JavaScript Promise
object can be in one of three states: pending
, resolved
, or rejected
.
While the value is not yet available, the Promise
stays in the pending
state. Afterwards, it transitions to one of the two states: resolved
or rejected
.
A resolved promise stands for a successful completion. Due to errors, the promise may go in the rejected
state.
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. Otherwise, an alert will be shown.
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory