Summary of how to use javascript Promise, javascriptpromise

Source: Internet
Author: User

Summary of how to use javascript Promise, javascriptpromise

The nested callback function is too deep, and the parallel logic must be executed in a serial manner. A Promise represents the final result of an asynchronous operation. The main way to interact with Promise is through its then () method to register the callback function and receive the final result value of Promise.

Promise-related protocols include PromiseA and PromiseA +

Define a class Promise

Define the attribute queue and initialize an empty array []

Defines the property value and initializes null.

Define the attribute status and initialize "pending" (default)

Define the member method getQueue () and return the attribute queue.

Define the member method getStatus () and return the property status.

Define the member method setStatus (), set the status, pass the parameter: status, value

Determine whether the status is fulfilled or rejected,

Set the status attribute this. status = status

Set the value attribute this. value = value | null. If no value is passed, this is null.


Define freeze variable freezeObject

Define the member method isFulfilled () to determine whether the current status is (complete)

Define the member method isRejected () to determine whether the current status is (failed)

Define the member method isPending () and determine whether the current status master is (waiting)

Define the member method then (), pass the parameter: onFulfilled success callback, onRejected failure callback

Define two callback functions: handler object, fulfilled and rejected.

Define the deferred attribute of the handler object.

Determines whether the current status is waiting. If the handler object is waiting to be inserted into the queue array

If not, call the procedure () method of the Utils object. Parameter: status,

Returns the handler. deferred. promise object.


Define a class Deferred

Define the property promise and initialize the Promise object.

Define the member method resolve () and pass the parameter: result

Determines whether the Promise object is in the waiting state and returns the result directly.

Call the getQueue () method of the Promise object to obtain the queue Array

Loop Array

// Todo calls the Utils. procedure () method of the tool class. The parameter is "fulfilled", element, and err information.

Call the setStatus () method of the Promise object and set the status. parameters: 'fulfilled' and result


Define the member method reject and pass the parameter err error message.

Determines whether the Promise object is in the waiting state and returns the result directly.

Call the getQueue () method of the Promise object to obtain the queue Array

Loop Array

// Todo: Call the Utils. procedure () method of the tool class. The parameter is "rejected", element, and err information.

Call the setStatus () method of the Promise object and set the status. parameters: 'fulfilled' and result


Define the tool class Utils and use anonymous functions to execute immediately to get an object
 
Returned object, which has a method procedure ()

Define the procedure () method, pass the parameter: type status type, handler processor array, result

Obtain the processing function func, in handler [type]

Here I am dizzy...
 

Usage:

Defines a function ajax, passing parameters: url path
 

Get the Deferred object, new

Ajax request data code, in the callback method of the returned data

If the resolve () method of the Deferred object is successfully called, parameter: returned data

If the call to the reject () method of the Deferred object fails, the parameter: returned data

Returns the Deferred. promise object.


Call the ajax () method to obtain the promise object, parameter: url,

Call the then () method of the promise object. The parameter is an anonymous function.

Call the ajax () method to obtain the promise object and return this object.

Form a chain call
 

Js section:

<Script> // Promise code section (I select a dog's belt) Promise = function () {this. queue = []; this. value = null; this. status = 'Pending'; // pending fulfilled rejected}; Promise. prototype. getQueue = function () {return this. queue;}; Promise. prototype. getStatus = function () {return this. status ;}; Promise. prototype. setStatus = function (s, value) {if (s = 'fullfiled' | s = 'objected') {this. status = s; this. value = value | | Null; this. queue = []; var freezeObject = Object. freeze | function () {}; freezeObject (this); // The promise state is irreversible} else {throw new Error ({message: "doesn't support status: "+ s}) ;}}; Promise. prototype. isFulfilled = function () {return this. status === 'fullfiled';}; Promise. prototype. isRejected = function () {return this. status = 'objected';} Promise. prototype. isPending = function () {return th Is. status = 'Pending';} Promise. prototype. then = function (onFulfilled, onRejected) {var handler = {'fullfiled': onFulfilled, 'objected': onRejected}; handler. deferred = new Deferred (); if (! This. isPending () {// you can add a callback utils after changing the promise status. procedure (this. status, handler, this. value);} else {this. queue. push (handler); // then may be called multiple times on the same promise; specification 2.2.6} return handler. deferred. promise; // then must return a promise; specification 2.2.7}; var utils = (function () {var makeSignaler = function (deferred, type) {return function (result) {transition (deferred, type, result );}}; Var procedure = function (type, handler, result) {var func = handler [type]; var def = handler. deferred; if (func) {try {var newResult = func (result); if (newResult & typeof newResult. then = 'function') {// thenable // This write method has a closure that may easily cause memory leakage. we solve this problem using high-order functions. // newResult. then (function (data) {// def. resolve (data); //}, function (err) {// def. reject (err); //}); // PromiseA + specification, x indicates newResult, and promise indicates def. pro Mise // If x is a promise, adopt its status [3.4]: // If x is pending, promise must remain pending until x is fulfilled or rejected. // If/when x is fulfilled, fulfill promise with the same value. // If/when x is rejected, reject promise with the same reason. newResult. then (makeSignaler (def, 'fullfiled'), makeSignaler (def, 'objected'); // The essence here is that asynchronous closure} else {transition (def, type, newResult) ;}} catc H (err) {transition (def, 'objected', err) ;}} else {transition (def, type, result) ;}}; var transition = function (deferred, type, result) {if (type = 'fullfiled') {deferred. resolve (result);} else if (type = 'objected') {deferred. reject (result);} else if (type! = 'Pending') {throw new Error ({'message': "doesn' t support type:" + type}) ;}; return {'Procedure ': procedure}) (); Deferred = function () {this. promise = new Promise () ;}; Deferred. prototype. resolve = function (result) {if (! This. promise. isPending () {return;} var queue = this. promise. getQueue (); for (var I = 0, len = queue. length; I <len; I ++) {utils. procedure ('filled', queue [I], result);} this. promise. setStatus ('filled', result) ;}; Deferred. prototype. reject = function (err) {if (! This. promise. isPending () {return;} var queue = this. promise. getQueue (); for (var I = 0, len = queue. length; I <len; I ++) {utils. procedure ('objected', queue [I], err);} this. promise. setStatus ('objected', err );}, split line ************************************/// test part ajax = function (url) {var def = new Deferred (); var xhr = new XMLHttpRequest (); xhr. onreadystatechange = Function () {if (xhr. readyState = 4) {if (xhr. status >=200 & xhr. status <300) | xhr. status = 304) {def. resolve (xhr. responseText)} else {// simplified ajax, error callback def not provided. reject (new Error ({message: xhr. status}) ;}}}; xhr. open ('get', url, true); xhr. send (null); return def. promise;} ajax ('test. php? Act = 1'). then (function (data1) {console. log (data1); // process data1 return ajax ('test. php? Act = 2');}). then (function (data2) {console. log (data2); // process data2 return ajax ('test. php? Act = 3');}, function (err) {console. error (err );}). then (function (data3) {console. log (data3); alert ('success') ;}, function (err) {console. error (err) ;}); </script>

Php:

<?phpif($_GET['act']==1){  echo json_encode(array("code"=>200));}else if($_GET['act']==2){  echo json_encode(array("code"=>300));}else if($_GET['act']==3){  echo json_encode(array("code"=>400));}

The summary of the above javascript Promise simple learning and use method is all the content that I have shared with you. I hope you can give us a reference and support for the help house.

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.