ES6 new feature 6: Detailed description of the promise object instance, es6promise

Source: Internet
Author: User

ES6 new feature 6: Detailed description of the promise object instance, es6promise

This example describes the promise object of the new ES6 feature. We will share this with you for your reference. The details are as follows:

1. Introduction to promise

It is an object, which is similar to other JavaScript objects. Second, it acts as a proxy ),Acts as an intermediary between asynchronous operations and callback Functions. It enables asynchronous operations to have interfaces for synchronous operations, so that the program has a normal synchronous operation process, and the callback function does not need to be nested layer by layer.

The idea is that every asynchronous task immediately returns a Promise object. Because it returns immediately, you can adopt a synchronous operation process. This Promises object has a then method that allows you to specify a callback function and call it after an asynchronous task is completed.

Asynchronous f1 operation returns a Promise object. The callback function f2 is written as follows:

(new Promise(f1)).then(f2);

2. Three states of the promise object

① Asynchronous Operation unfinished (pending)
② Asynchronous Operation completed (resolved)
③ Asynchronous operation failed (rejected)

3. Working Process

The Promise object uses the then method to add a callback function. The then method can accept two callback functions. The first is the callback function when the asynchronous operation is successful (changes to the resolved State), and the second is the asynchronous operation failure (changes to rejected) callback Function (can be omitted ). Once the status changes, the corresponding callback function is called,Both callback functions take the value returned by asynchronous operations as a parameter..

promise.then( console.log, console.error);

4. Chain use of then

① First, a new promise object returned by the then method, so the method can be chained.

② The first parameter of the then method is the callback function in the Resolved state, and the second parameter (optional) is the callback function in the Rejected state.

③ As shown in the following figure, once the promise status changes to resolved, the callback function specified by every then is called in sequence. Each step will be executed only after the previous step is completed. The callback functions console. log and console. error of the last then method have an important difference in usage. Console. log only displays the returned values of the callback function Step 3. console. error can display any of the errors in step 1, step 2, and step 3. Errors of the Promises object are passed.

promise .then(step1) .then(step2) .then(step3) .then(  console.log,  console.error );

5. Use of promise object

Var promise = new Promise (function (resolve, reject) {// constructor of promise. The Promise constructor accepts a function as a parameter, the two parameters of this function are resolve and reject // code for asynchronous operations if (/* Asynchronous Operation successful */) {resolve (value ); // pass the asynchronous operation result as a parameter} else {reject (error );}});

The resolve and reject functions are provided by the JavaScript engine and do not need to be deployed by yourself.

The role of the resolve function: changes the state of the Promise object from "incomplete" to "successful" (I .e., from Pending to Resolved), calls the result of the asynchronous operation when the asynchronous operation is successful, and, passed as a parameter;

The role of the reject function: changes the state of the Promise object from "incomplete" to "failed" (I .e., from Pending to Rejected) and calls it when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.

① The following is an example of Ajax operations implemented using the Promise object.

Var getJSON = function (url) {var promise = new Promise (function (resolve, reject) {var client = new XMLHttpRequest (); client. open ("GET", url); client. onreadystatechange = handler; client. responseType = "json"; client. setRequestHeader ("Accept", "application/json"); client. send (); function handler () {if (this. readyState! = 4) {return;} if (this. status = 200) {resolve (this. response); // will pass the parameter to the callback function} else {reject (new Error (this. statusText) ;}};}); return promise ;}; getJSON ("/posts. json "). then (function (json) {console. log ('contents: '+ json);}, function (error) {console. error ('error error', error );});

② In addition to normal values, the parameters of the resolve function may also be another Promise instance. That is, the result of an asynchronous operation is to return another asynchronous operation.

var p1 = new Promise(function (resolve, reject) { // ...});var p2 = new Promise(function (resolve, reject) { // ... resolve(p1);})

6. Promise. prototype. catch ()

① A Promise object. If an Asynchronous Operation throws an error, the state changes to Rejected, and the callback function specified by the catch method is called to handle the error.

Promise. then (function (posts ){//...}). catch (function (error) {// error console when processing getJSON and the previous callback function. log ('An error occurred! ', Error );});

② In addition, the callback function specified by the then method will be caught by the catch method if an error is thrown during running.

var promise = new Promise(function(resolve, reject) { throw new Error('test');});promise.catch(function(error) { console.log(error);});// Error: test

③ Two other statements

// Write var promise = new Promise (function (resolve, reject) {try {throw new Error ('test');} catch (e) {reject (e) ;}}); promise. catch (function (error) {console. log (error) ;}); // method 2 var promise = new Promise (function (resolve, reject) {reject (new Error ('test ')); // The Role Of The reject method, equivalent to throwing an error}); promise. catch (function (error) {console. log (error );});

④ Errors thrown after the resolve Statement by Promise will not be captured. Because once the Promise status changes, it will be permanently maintained and will not change.

var promise = new Promise(function(resolve, reject) { resolve('ok'); throw new Error('test');});promise .then(function(value) { console.log(value) }) .catch(function(error) { console.log(error) });// ok

7 Promise. all ()

The parameter is an array of Promise objects. Multiple Promisre objects are encapsulated into a new Promise object. If the array is not a Promise object, Promise is automatically called. the resolve method converts parameters to Promise instances for further processing. (Parameters of the Promise. all method can be not arrays, but must have the Iterator interface, and every returned member is a Promise instance)

var p = Promise.all(promises).then(function (posts) { // ...}).catch(function(reason){ // ...});

① As long as one of promises changes to rejected, p changes to rejected. At this time, the return value of the first reject instance will be passed to p's callback function.
② If all objects are changed to resolved, the returned values of all objects in the promises array constitute an array and are passed to the p callback function.

8 Promise. resolve ()

To convert an existing object to a Promise object, the Promise. resolve method plays this role.

Promise. resolve ('foo') // equivalent to new Promise (resolve => resolve ('foo '))

① The parameter is a Priomise object, and Promise. resolve () is not processed.
② The parameter is an object with the then method: the Promise. resolve Method converts this object into a Promise object, and then immediately executes the then method of the thenable object.

Let thenable = {then: function (resolve, reject) {resolve (42) ;}; let p1 = Promise. resolve (thenable); // p1 is a promise object whose status is already resolved. p1.then (function (value) {console. log (value); // 42 });

③ The parameter is not an object with the then method, or is not an object at all.

This parameter is changed to the resolve () parameter of the generated Promise object.

Var p = Promise. resolve ('hello'); // The resolve () p. then (function (s) {console. log (s)}); // Hello

I hope this article will help you design the ECMAScript program.

Related Article

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.