Sometimes you may need to create an already
fulfilled promise. There are two methods
for this: the Promise.resolve
method
creates a resolved promise, Promise.reject
creates a rejected promise. As a parameter,
these methods receive what will become
the result or error of the promise,
respectively.
When might we need an already fulfilled promise? Let's look at an example. Suppose we have some function that takes a number as a parameter, does something with it asynchronously and returns a promise with the result:
function func(num) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(num * num);
}, 3000);
});
}
We will use our function as follows:
func(5).then(function(res) {
console.log(res); // shows 25
});
Let us now decide that we will perform our asynchronous operation only if a number greater than zero is passed. Otherwise, the result of the function must be zero:
function func(num) {
if (num > 0) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(num * num);
}, 3000);
});
} else {
return 0; // a result is 0
}
}
However, now it turns out that the function
returns either a promise or a number. Because
of this, we can no longer apply the then
method to the result of the function, since
if the function returns a number, we will get
an error:
func(0).then(function(res) { // an error, we apply the then method to 0
});
Promise.resolve
will help
us fix the problem:
function func(num) {
if (num > 0) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(num * num);
}, 3000);
});
} else {
return Promise.resolve(0); // returns a promise, not a number
}
}
Let us now decide that for the passed zero
we should return zero, and for numbers less
than zero - an exception. The Promise.reject
method will help us with this:
function func(num) {
if (num > 0) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(num * num);
}, 3000);
});
} else if (num === 0) {
return Promise.resolve(0);
} else {
return Promise.reject('incorrect number'); // returns a rejected promise
}
}