The Promise then() Function in JavaScript
A promise in an asynchronous task in JavaScript that will return a Promise
object, which can be accessed using the then()
function. In this tutorial, we will learn how to create promises in JavaScript and use them with the then()
function.
Promise then() Basic Useage
Promises in JavaScript are essentially a placeholder for an operation that is waiting to be used. There are three states of a promise; pending, fulfilled and rejected. The latter two are generated when the then()
function is called, meaning we can handle the success or failure of a promise.
var promise = new Promise(function(resolve, reject) {
// do something that returns true or false.
if (result) {
resolve("Somthing worked");
}
else {
reject(Error("Didn't work"));
}
});
promise.then(function(result) {
console.log(result);
}, function(err) {
console.log(err);
});
Somthing worked
Immediately Resolve a Promise
To immediately resolve a Promise
, we can all the resolve()
method immediately and pass a value inside the ()
(parenthesis) of the method.
const promise = Promise.resolve('hello');
At this point, the Promise
object will still be in a pending state. To complete it, and in this case, fulfil the promise we can call the then()
function on the Promise
object and pass the value to an anonymous function.
promise.then(val => {
console.log(val);
});
hello
Immediately Reject a Promise
To immediately reject a Promise, can use the reject()
method and create a new Error()
inside the ()
(parenthesis) of the method.
const promise = Promise.reject(new Error('Problem: FOO'));
promise.then(null, err => {
console.log(err.message);
});
Problem: FOO
The difference when getting a pending rejection with the then()
function is it will be on the second parameter of it. Since we don't have a pending resolve, the first argument of then()
can be null
.
Using the catch() Function
The only difference between the catch()
and then()
Promise
functions is that the rejected promise is used as the first parameter on catch()
, which can be more convenient to write.
const promise = Promise.reject(new Error('Problem: FOO'));
promise.catch(val => {
console.log(val.message);
});
Problem: FOO
Conclusion
You now know how to use promises in JavaScript with the then()
and catch()
functions to complete a pending promise to a rejected or fulfilled state.