Creating Promises — Javascript Promises: part II
On the first part of this series, we talked a little bit about what is a Promise and how to work with it, click here to check it out. On this article I’ll follow from the first part.
Now, it’s time to create a Promise of our own.
Creating Promises
Promises can be created using the Promise
object. It’s quite simple, actually.
The Promise
constructor receives a function and this function has two arguments: resolve
and reject
.
const promise = new Promise((resolve, reject) => {
//...
});
Both resolve
and reject
are callables. As the name suggests you must call resolve
when the Promise is resolved (in other words, when it succeeds); and call reject
when the Promise has an error.
const promise = new Promise((resolve, reject) => {
if(somthing) {
resolve('success');
} else {
reject('error');
}
});
In this example, if something
is true
the resolve
method will be called and will resolve the Promise. Otherwise, the Promise will be rejected with error
message.
Let’s consume this Promise:
promise.then(result => console.log(result))
.catch(err => console.error(err));
In this case, if something
is true
the then
method will be invoked. The result
variable will receive the success
string (in other words, whatever was informed on resolve
method). Otherwise, the catch
method will be invoked and the err
variable will receive the error
string (in other words, whatever was informed on reject
method).
As we learned on the previous part, we could also do the following:
promise.then(
result => console.log(result),
err => console.error(err)
);
And it will produce the same behavior.
When things execute
Here things might get confused. But never forget this rule: Promises always execute immediately!
Let me explain with another code:
console.log("Log 1");const promise = new Promise(resolve => {
console.log("Log 2");
resolve();
});console.log("Log 3");promise.then(result => {
console.log("Log 4");
});console.log("Log 5");
How do you think will be the output?
Log 1
Log 2
Log 3
Log 5
Log 4
Here we see clearly the Promise executes right away since Log 2
is shown after Log 1
and before Log 3
.
However, Log 4
will only execute after Log 5
. And why does it happen?
Well, it is because of the event loop. I’ll not cover it right now, but basically the methods called by a Promise ( then
and catch
) will always execute after the main execution is over.
There are so many details on it, if you are not aware of how event loop works, I recommend researching it a little bit.
Disclaimer
I’m using Promises here in order to explain how they work. In a real world situations you shouldn’t use them like this.
You only use a Promise when you need to execute something that might take a while to finish. Like an API request, a database query, and things like that…
On the next part, let’s cover async
and await
. See you there!
Cheers!