Basic knowledge: Promise (finishing)

Source: Internet
Author: User

Basic knowledge: Promise (finishing)

(from the Cattle network) The following statement about promise, the wrong is (D)
A. Both resolve and reject directly generate a promise object that enters the corresponding state, and its parameters are passed in the corresponding state when passing parameters, which can be obtained in the parameters of the completion callback
B. Promise.resolve (value), promise.reject (reason) is a set of static methods that are also directly provided on the Promise constructor
C. is asynchronous when the then method or catch method is called, but executes faster
D. There are also two methods on the prototype of the promise constructor, namely then and catch. The parameters of these two methods are also callback functions that are called after the promise instance enters a different state. then correspond to the resolve,catch corresponding to the Reject. (Personal understanding is that "then corresponds to resolve" here is wrong, then can accept two callback functions as parameters.) The first callback function is called when the state of the Promise object becomes resolved , and the second callback function is called when the state of the Promise object changes to rejected . Where the second function is optional)

1. Concept

Promise, in short, is a container that holds the result of an event (usually an asynchronous operation) that will end in a future. Syntactically, is an object that is used to pass the message of an asynchronous operation. It represents an event in the future that will know the result (usually an asynchronous operation), and this event provides a unified API for further processing.

The Promise object has the following two characteristics.

(1) The state of the object is unaffected by the outside world. The Promise object represents an asynchronous operation with three states:Pending(initial state),resolved(completed, also known as fulfilled), and rejected(failed). Only the result of an asynchronous operation can determine which state is currently, and no other operation will change that state. This is also the origin of the name Promise, its English meaning is "commitment", that other means can not be changed.

(2) Once the state changes, it will not change, and can get this result at any time. There are only two possible changes to the state of the Promise object: from Pending to resolved and from Pending to rejected. As long as these two situations occur, the state is solidified and will not change, and will keep the result. Even if the change has occurred, you can add a callback function to the Promise object, and you will get the result immediately. This is quite different from the event, which is characterized by the event that if you miss it and then listen to it, you won't get the result.

With the Promise object, the asynchronous operation can be expressed in the process of synchronous operation, avoiding the nested callback functions of layers. In addition, the Promise object provides a unified interface that makes it easier to control asynchronous operations.

Promise also has some drawbacks. First, the Promise cannot be canceled, and once it is newly created it executes immediately and cannot be canceled halfway. Second, if you do not set a callback function, the Promise inside throws an error and does not react externally. Third, when in the Pending state, it is not possible to know the current progress to which stage (just beginning or nearing completion).

2. Basic usage

The Promise object is a constructor that is used to generate an promise instance.

1 //a Promise instance was created2 varPromise =NewPromise (function(Resolve, reject) {3   //... some code4 5   if(/*Asynchronous Operation succeeded*/){6 Resolve (value);7}Else {8 reject (error);9   }Ten});

The promise constructor takes a function as a parameter, and the two parameters of the function are resolve and reject. They are two functions that are provided by the JavaScript engine and are not deployed on their own.

The purpose of the Resolve function is to change the state of the promise object from unfinished to successful (that is, from Pending to resolved), to invoke when the asynchronous operation succeeds, and to pass the result of the asynchronous operation as a parameter The Reject function is to pass the state of the Promise object from "unfinished" to "failed" (that is, from Pending to rejected), when the asynchronous operation fails, and the error reported by the asynchronous operation as a parameter.

After the promise instance is generated, you can use the then method to specify the callback function for the resolved state and the rejected state, respectively.

1 promise.then (function(value) {2   //  success3 function (Error) {4   // Failure 5 });

The then method can accept two callback functions as arguments. The first callback function is called when the state of the Promise object becomes resolved , and the second callback function is called when the state of the Promise object changes to rejected . Where the second function is optional and not necessarily provided. Both of these functions accept the value of the Promise object as an argument.

Promise.prototype.then () The promise instance has the then method, that is, the then method is defined on the prototype object Promise.prototype. Its purpose is to add a callback function to the promise instance when the state changes. As I said before, the first parameter of the then method is the callback function for the resolved state, and the second argument (optional) is the callback function for the rejected state.

The then method returns a new promise instance (note that it is not the original promise instance).

Promise.prototype.catch () The Promise.prototype.catch method is an alias for. Then (null, rejection), which specifies the callback function when an error occurs.

But when using this method, pay attention to the following points:
(1) When the Promise State has become resolved , it is invalid to throw an error again. Look at the code below.

var promise=New Promise (function(resolve,reject) {   Resolve ("OK");    Throw New Error ("test");      }); Promise.then (function(value) {Consloe.log (val);})            . Catch (function(error) {Console.log (ERR)});

The Promise State is resolve ("OK"), then the promise status is changed to resolved, and then the throw error does not change the promise state to rejected, so the catch method does not catch the error.

(2) Try to write the catch method at the end of the chain operation, and when the error continues to bubble to the end, the catch will catch all errors at the end. Errors that occur after the catch are not captured when the catch is set prematurely, and then there is no catch method.

(3) When there is no callback function that uses the Catch method to specify the error handler, the error thrown inside the Promise object is not passed to the outer code.

In general, do not define a callback function for the reject state in the then method (that is, then the second argument), always using the Catch method.

promise.resolve () The function of this method is to convert existing objects into Promise objects, which can then be executed.

Basic knowledge: Promise (finishing)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.