A Promise
is a promise from the producing code to the consuming code that I (the producing code) will return something that you (the consuming code) can work with.
The producing code is often something that takes time, so it is usually written in an asynchronous manner, allowing it to be executed in parallel with other less time-consuming tasks. The consuming code is something that needs to use the result of the producing code once it is ready.
The promise is what links them together. This is important because in practice, you cannot expect the producing code to always be successful. It is possible that the time-consuming task eventually fails and returns something that the consuming code cannot work with.
Compared to the callback style syntax we've seen in the previous lesson, promises offer a cleaner and more intuitive way of writing asynchronous programs.
The Promise constructor
A promise is created with a Promise
constructor, which has the following syntax:
1const promise = new Promise((resolve, reject) => {
2 . . . // Producing code
3});
The Promise
constructor accepts a function argument, which contains the producing code. The function takes two callbacks as the input, resolve()
and reject()
.
The producing code will be executed immediately when new Promise()
is created, and if it gives the right outcome, resolve()
should be executed. And if something goes wrong, reject()
should be executed. For example,
1const promise = new Promise((resolve, reject) => {
2 const rand = Math.random() * 100;
3
4 if (rand >= 50) {
5 resolve(rand);
6 } else {
7 reject(new Error("Random number is less than 100"));
8 }
9});