For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more.

2025/07/0506:36:38 hotcomm 1945

Promise is one of the solutions for asynchronous programming, which is more reasonable and powerful than traditional callbacks and event mechanisms.

scene example

One day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind.

The carpenter will respond to any request, that is, once the email is sent, he will get his promise (Promise): I will do my best. The method for notifying the result in the mail specified in the mail:

succeeded, and directly mail the furniture (res) to the mail.

failed and sent the failed message (err) directly to email (reject).

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

email is equivalent to getting the promise P from the carpenter. After that, all you can do is wait (then).

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

behavioral characteristics

status

Each Promise has three states: in progress (pending), has succeeded (resolved) and has failed (rejected).

is created and enters the pending state. Once the resolve/reject method is called in the incoming method, the final state becomes resolved/rejected. Once

becomes the result state, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more.

1.State container

Promise is essentially a state container. After

gets the result status, you can access this status at any time.

This is different from event subscription notifications, and if the subscription occurs after the notification, the subscription does not work.

2. The status is uncontrollable

Once a Promise is created, it will be executed immediately and cannot be cancelled. When

is in the pending state, it is impossible to know the specific information of the process, such as the completion percentage (although you can set the callback to notify yourself).

3. Failed state

Successful state can only be converted from the resolve method. The failure status of

can be converted from reject method or indirectly from throwing an error.

and all three will print out the failed information normally.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

4. Error reporting mechanism

If the failed state does not receive the failed callback function , Promise will throw an error. The throwing error here in

is just a prompt displayed on the console, and will not terminate the program's process.

prints out 'err' first, and then an error is reported.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

Once the Promise has set the failed callback function, even if the code execution is incorrect, it will be digested by itself and will not be reported out.

Although a is not defined, it is quiet throughout the process and has no fuss.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

Execution order

1. Passing method

0 Create a Promise and also executes the pass-through method.

passed in method will not terminate the execution just because resolve/reject is called, so the better way is to retrun resolve/reject.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

2. Callback method

immediately obtains the result Promise, and its callback function will still be executed later than this round of events.

, which is different from setTimeout, pushes the execution function to the execution stack, but puts the execution function at the end of this round.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

3. Result parameter

The parameter passed in reject is generally a string or an Error instance, indicating the error thrown.

passed the resolve parameter, which is generally the corresponding JSON data, etc., to represent the obtained data.

passes the resolve parameter, and it can also be another Promise instance.

At this time, the outer layer promise will only end after the inner layer promise is completed.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

In this case, if the inner layer fails, it does not mean passing an Error instance to resolve differently.

The former is the inner layer Promise that throws an error and will be caught by the outer layer, and the latter is just the parameter of an Error instance.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

instance method

then()

This method can pass in two, corresponding to the callback functions when success/failure.

This method returns a new Promise object, which is also the reason why chained (.then.then...) can be used.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

1.return

chain, the state of the latter depends on the result returned in the callback function of the former (success/failure).

If it does not return, it returns a successful state with a value undefined.

If returned as a Promise object, the state of the latter is determined by the final state of the object.

If data is returned as non-Promise objects, it will return a successful state, and the value is this data.

If an error is thrown when executing the former, it is equivalent to returning a failed state, and the value is this error.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

2. State transfer

In the chain, if the former state is not captured by the latter, it will continue to bubble (like) until it is captured. The

state disappears after being captured. The state after this is determined by the current returned state and is repeated later.

is printed out in sequence:

2 res 2000

3 res 3000

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

catch()

is used to specify the callback function when an error occurs, equivalent to: .then(null, callback).

's performance is consistent with that of then, such as returning a new promise, inheritance and delivery of state, etc.

is generally recommended to use catch instead of the second method of then to receive errors.

Because catch can catch then its own errors, it is closer to the synchronous writing method (try/catch).

new Promise(() = {}).then(() = { ...}).catch(() = { ...});

finally()

is used for the final work after the Promise processing is completed. The callback function passed into

will not accept any parameters, meaning there is no way to know the result of the Promise.

This also shows that the operations in finally have no relationship with the status and do not rely on the processing results of the Promise.

is the same essence as catch, and is also a variant of the then method.

However, it is just the transmitter of the state, it will only return to the original state, will not receive the state and create a new state.

p.finally(() = { // codes...});

--- equivalent to

p.then(res = { // codes... return res; // Return the original successful state}, err = { // codes... throw err; // Return the original failed state});

Example

When requesting data, we will display the loading pattern. After the request is completed, this pattern must be hidden regardless of the result.

Generally, the structure of a complete Promise will be as follows.

showLoading = true;new Promise((resolve, reject) = { // Request...}).then(res = { // Successfully processed...}).catch(err = { // Failure processing...}).finally(() = { // Reset some states... showLoading = false;});

Static method

resolve()

This method directly returns a Promise with a status resolved and a value of its parameter.

Promise.resolve(res);

--- equivalent to

new Promise(resolve = resolve(res));

reject()

This method directly returns a Promise with a status rejected and its parameter.

Promise.reject(res);

--- equivalent to

new Promise((resolve, reject) = reject(res));

all()

This method is used to wrap multiple Promise instances into a new Promise instance.

has an array of parameters, and each item should be a Promise instance (not, it will be converted using Promise.resolve).

The state of the new Promise depends on the final state of each item passed in the array.

If an item's status becomes rejected, the new instance is rejected, and the value is the return value of the item.

If all items become resolved, the new instance is resolved, and the value is an array containing the returned values ​​for each item.

Three seconds later, print out: [1, 2, 3].

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

race()

This method is basically the same as all(), and the parameters passed in are also a Promise array.

The difference is that the final state of the new Promise is determined by the item (success or failure) that changes the first state in the array.

After one second, 1 is printed out.

For example, one day, I had a sudden idea and sent an email to the carpenter to customize a furniture of this kind. Once it becomes the result state, that is, it is changed to resolved/rejected, and the state is frozen and cannot be changed any more. - DayDayNews

Programming is a kind of practice. I am willing to work hand in hand with like-minded friends to explore the mysteries of programming together!

If you encounter difficulties in front-end learning, welcome to [Follow] and [Private Message] me, and everyone will communicate and solve it together!

Recommended article:

JS Generator function you don't know (Part 1)

JS Generator function you don't know (Part 2)

hotcomm Category Latest News