How much do you know about Promise?

Mondo Health Updated on 2024-02-24

Promises are a solution for asynchronous programming that makes more sense and is more robust than traditional solutions - functions and events. It was first proposed and implemented by the community, and ES6 has written it into language standards, unifying usage, and natively providing promise objects.

Promise objects have two characteristics.

(1) The state of the object is not affected by the outside world.

The promise object represents an asynchronous operationThere are three states: pending, resolved (also known as fulfilled), and rejected。Only the result of an asynchronous operation can determine which state it is in, and no other operation can change this state. This is where the name promise comes from, which means "promise" in English, meaning that it cannot be changed by other means.

(2) Once the state changes, it will not change again, and this result can be obtained at any time.

promise objectThere are only two possibilities: from pending to resolved and from pending to rejected。As long as these two situations occur, the state will be solidified, it will not change again, and it will always maintain this result. Even if the change has already happened, you can add a function to the promise object and you will get this result immediately. This is completely different from an event, which is characterized by the fact that if you miss it and listen to it, you won't get results.

With the promise object, you can express asynchronous operations in the flow of synchronous operations, avoiding layers of nested functions. In addition, promise objects provide a unified interface that makes it easier to control asynchronous operations.

Promises also have some drawbacks. First of all, a promise cannot be canceled, and it will be executed immediately once a new promise is created, and cannot be canceled halfway. Secondly, if you don't set the ** function, the error thrown inside the promise will not be reflected externally. Third, when in the pending state, there is no way to know what stage you are currently in (just started or about to finish).

Example 1: Basic usage.

var promise = new promise(function(resolve, reject) else }
Example 2: As soon as a new promise is made, it will be executed immediately.

let promise = new promise(function(resolve, reject) )promise.then(function() console.log('hi!'); // promise // hi! // resolved
Example 3: Here's an example of an AJAX operation implemented with a promise object. (Very classic).

var getjson = function (url) if (this.status === 200) else }return promise; }getjson("/posts.json").then(function (json) ,function (error) )
Promise instances have a then method, that is, the then method is defined in the prototype object promiseprototype. What it does is add a function to the promise instance when the state changes. As mentioned earlier, the first argument to the then method is a function of the resolved state, and the second argument (optional) is a function of the rejected state.

The then method returns a new promise instance (note that it is not the original promise instance). So you can use the chained approach, where the then method is followed by another then method.

getjson("/posts.json").then(function(json) )then(function(post) )
With chained then, you can specify a set of functions that are called sequentially. In this case, the previous function may still return a promise object (that is, there is an asynchronous operation), and the latter function will wait for the state of the promise object to change before it is called.

getjson("/post/1.json").then(function (post) )then(function funca(comments) ,function funcb(err) )
In the first then method above, the function specified by the first then method returns another promise object. In this case, the second then method specifies a function that waits for the state of the new promise object to change. If it becomes resolved, it calls funca, and if the state changes to rejected, it calls funcb.

promise.prototype.The catch method is. then(null, rejection) to specify the ** function when an error occurs.

Example:

getjson("/posts.json").then(function (posts) )catch(function (error) )
Unlike the traditional try catch block, if there is no function that uses the catch method to specify error handling, the error thrown by the promise object will not be passed to the outer layer, i.e. there will be no reaction.

var someasyncthing = function ()someasyncthing().then(function ()
promise.The all method is used to wrap multiple promise instances into a new promise instance.

var p = promise.all([p1, p2, p3]);

Above, promiseThe all method accepts an array as an argument, and p1, p2, and p3 are all instances of the promise object.

Example:

promise.all([checklogin(),getuserinfo()]then(([res1,res2])=>, result2:$`
promise.The race(iterable) method returns a promise that is resolved or rejected once a promise in the iterator is resolved or rejected.

Sometimes you need to convert an existing object into a promise object, a promiseThis is where the resolve method comes in.

var jspromise = promise.resolve($.ajax('/whatever.json'));
promise.The reject(reason) method also returns a new promise instance with a state of rejected. Its arguments are used in the same way as promiseThe resolve method is identical.

ES6's promise API doesn't provide many methods, and there are some useful methods that you can deploy yourself. Here's how to deploy two useful methods that aren't part of ES6.

9.1. The ** chain of the done()promise object, whether it ends with the then method or the catch method, if the last method throws an error, it may not be caught (because the error inside the promise will not bubble to the whole world). Therefore, we can provide a done method, which is always at the end of the chain, and is guaranteed to throw any errors that may occur.

asyncfunc() then(f1) .catch(r1) .then(f2) .done();
9.2. The finally()finally method is used to specify the operation that will be performed regardless of the final state of the promise object. The biggest difference between it and the done method is that it accepts a normal ** function as an argument, which must be executed anyway.

server.listen(0) .then(function ()finally(server.stop);
The generator function is used to manage the process, and when an asynchronous operation is encountered, a promise object is usually returned.

function getfoo() var g = function* (catch (e) function run(generator) ,function (error) )go(it.next())run(g);
Ultra-detailed Promise Understanding and ImplementationFront-end Promise Common Application ScenariosCorrect Understanding Posture of Promise Execution Process [J**Ascript]Handwritten Promise Must Be Able to Deeply Demystify Promise Microtask Registration and Execution ProcessPromise Principle and ImplementationUltra-detailed Promise Understanding and Implementing Front-end Promise Common Application ScenariosCorrect Understanding Posture of Promise Execution Process【J** ascript] must be able to write a handwritten promise, add it: promiseallsettled()

Direct reference to the documentation:

Related Pages