Promise usage in JavaScript

Time:2020-11-24

Promise initial

Promise is a solution of asynchronous programming. Promise can be regarded as an object from which messages of asynchronous operation can be obtained. Promise provides a unified API, and all kinds of asynchronous operations can be handled in the same way. It has two characteristics

  1. The state of the object is not affected by the outside world. A promise object represents an asynchronous operation. There are three states: pending, fulfilled, and rejected. Only the result of promise execution can affect the current state, whether asynchronous or synchronous.
  2. Once the state changes, it doesn’t change again. You can get this result at any time. There are only two possibilities to change the state of a promise object: from pending to fulfilled and from pending to rejected.

Basic Usage

ES6 specifies that promise object is a constructor used to generate promise instances.

new Promise(
    /* executor */
    function(resolve, reject) {...}
);

The promise constructor takes a function as an argument. The two parameters of the function are resolve and reject. They are two functions that are provided by the JavaScript engine and do not need to be deployed by yourself. Take an example:

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// resolved

You can see that when a new promise is created, the parameter function in the promise constructor will be executed immediately, that is, the function containing the resolve and reject methods will be executed immediately. In the above code, promise will be executed immediately after it is created, so the first output is promise. Then, the callback function specified by the then method will not be executed until all synchronization tasks of the current script have been executed, so resolved will output the final output.
be careful:
1. In the parameter function of promise, if one of the two functions, resolve and reject, is also a promise, then the state of the original promise will be determined by the state of promise in the parameter
The return function does not end

Then method

The then method is defined in the prototype object Promise.prototype On. Its function is to add a callback function when the promise instance changes state. The first parameter of the then method is the callback function of the resolved state, and the second (optional) parameter is the callback function of the rejected state. The then method returns a new promise instance (note that it’s not the original promise instance). So you can use chaining, that is, the then method is followed by another then method.

//Getjson is an instance of promise
getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});

Many times, some asynchronous operations will be written artificially in then, which can be called in chain. However, even if it is not an artificial asynchronous operation, JavaScript will automatically encapsulate the return value of then as promise instance, and then infinite callback can be used all the time.

Catch method

Promise.prototype.catch Method is an alias for. Then (null, rejection) to specify the callback function when an error occurs. If an asynchronous operation throws an error, the status changes to rejected and the callback function specified by the catch method is called to handle the error. In addition, the callback function specified by the then method will also be caught by the catch method if an error is thrown during operation.

//Getjson is a promise
getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  //Handle errors that occurred when getjson and the previous callback function were run
  console.log ('error! ', error);
});

The recommended writing method is to use then to add a resolve callback to project, and then use catch to catch all rejections or exceptions on the link.

promise.resolve understand

so to speak Promise.resolve It is the only operation that converts promise to completed state, Promise.resolve The parameters of the method are divided into four cases

  1. Parameter is a promise instance
    If the parameter is a promise instance, then Promise.resolve This instance will be returned intact without any modification. As mentioned before, if the resolve parameter of promise carries a promise, the original promise will be discarded and replaced by the new promise state
  2. The parameter is a thenable object
    Thenable objects are objects with then methods, Promise.resolve Method converts this object into a promise object and immediately executes the then method of the thenable object.
  3. The parameter is not an object with a then method, or is not an object at all
    If the parameter is an original value or an object that does not have the then method, then Promise.resolve Method returns a new promise object with the state resolved.
  4. Without any parameters
    Promise.resolve Method allows you to directly return a promise object in the resolved state without parameters.

promise.reject understand

Promise.reject The (reason) method also returns a new promise instance with the status of rejected.
be careful, Promise.reject The parameter of () method will be used as the reason of reject and become the parameter of subsequent method. This is related to Promise.resolve The method is inconsistent.

other

  1. done()
    The callback chain of promise object, whether ending with the then method or the catch method, may not be caught if the last method throws an error (because the error inside promise will not bubble to the global level). Therefore, we can provide a done method, always at the end of the callback chain, to ensure that any possible errors are thrown.
  2. done()
    The finally method is used to specify the operation to be performed regardless of the final state of the promise object. The biggest difference between it and the done method is that it takes a normal callback function as an argument, which must be executed anyway.

Recommended Today

Talking about Java collection

preface Most programming languages provide array to save objects, and array is one of the most important data structures. However, the length of the array has been defined during initialization, which is immutable and troublesome to use. Therefore, Java inJDK 1.2The collection framework is added to the version to save and manipulate objects. The container […]