JavaScript promise Simple Learning using method summary _javascript Skill

Source: Internet
Author: User

The resolution callback function is nested too deep, parallel logic must be serially executed, a promise represents the end result of an asynchronous operation, and the main way to interact with promise is to register the callback function through his then () method to receive the Promise final result value

Promise related protocols are Promisea and promisea+.

Define a class Promise

Define property queue queues, initialize empty arrays []

Defines the value of a property, initializing null

Define attribute state status, initialize "Pending" (default value)

Define member Method Getqueue (), returning property queue

Define member Method GetStatus (), Return property status

Define member Method SetStatus (), setting state, passing parameters: Status,value

Judge status as fulfilled or rejected,

Set the Status property This.status=status

Set Value Property This.value=value | | NULL, if value is not passed


define a frozen variable freezeobject

Define member Method Isfulfilled () to determine whether the current state is (completed)

Define member Method Isrejected () to determine if the current state is (failed)

Define member Method Ispending (), judge the current state master is (waiting)

Define member method then (), passing parameters: Onfulfilled Successful callback, Onrejected failed callback

Define object Handler object, property fulfilled,rejected two callback functions

Defines the deferred property of the handler object, deferred object

Determine whether the current state is waiting, if it is waiting to cram the handler object into the queue queue array

If it is not a wait state, invoke the procedure () method of the Utils object, parameter: status,

Returns the Handler.deferred.promise object


define a class deferred

Define attribute Promise, Initialize promise Object

Define member Method Resolve (), passing parameters: result results

To judge the state of a promise object is to wait, to return directly

Call the Getqueue () method of the Promise object to get the queue array

Loop array

Todo invokes tool class Utils. Procedure () method, Parameters: "Fulfilled", element, err information

Invokes the SetStatus () method of the Promise object, setting the state, parameter: ' fulfilled ', result


Define member method reject, passing parameters: Err error message

To judge the state of a promise object is to wait, to return directly

Call the Getqueue () method of the Promise object to get the queue array

Loop array

Todo, invoke Tool class Utils. Procedure () method, Parameters: "Rejected", element, err information

Invokes the SetStatus () method of the Promise object, setting the state, parameter: ' fulfilled ', result


Define the tool class Utils, execute immediately using the anonymous function, and get an object

Returns an object in which there is a method procedure ()

Defines the procedure () method, passing Parameters: type state types, handler processor arrays, result results

Get to processing function func, in Handler[type]

Here I am dizzy ...

How to use:

Define a function ajax, passing parameters: URL Path

Get deferred object, new out

Ajax requests the code of the data, in the callback method that returns the data

If you succeed in calling the deferred object's resolve () method, parameter: The returned data

If you fail to invoke the Reject () method of the deferred object, parameter: The returned data

Returns the Deferred.promise object


Invoke the Ajax () method to get the Promise object, parameter: URL,

Call the Promise object's then () method, parameter: anonymous function

Call the Ajax () method, get to the Promise object, return this object

Form a chained call

JS section:

<script>//promise Code section (I choose Dog Band) 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 = = ' fulfilled ', | | s = = ' rejected ') {this.status = s; This.value = value | |
    Null
    This.queue = []; var freezeobject = Object.freeze | |
    function () {}; Freezeobject (this);//Promise State is irreversible} else {throw new Error ({message: "doesn ' t support status:" + S}
  );
}
};
Promise.prototype.isFulfilled = function () {return this.status = = ' fulfilled ';};
Promise.prototype.isRejected = function () {return this.status = = ' rejected ';}
Promise.prototype.isPending = function () {return this.status = = ' pending ';} Promise.prototype.then = function (onfulfilled, onrejected) {var handler = {' Fulfilled ': onfulfilled, ' Rejected ': onrejected};

  handler.deferred = new deferred ();
  if (!this.ispending ()) {///Here allows the promise state to be changed before adding a callback Utils.procedure (This.status, Handler, this.value); else {This.queue.push (handler);//then May is called multiple times on the same promise; Spec 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 (DE
    ferred, 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//There is a closure that can easily result in a memory leak, we solve it by higher order function
          Newresult.then (function (data) {//Def.resolve (data);
          The function (ERR) {//Def.reject (ERR);
     // });     promisea+ specification, X represents newresult,promise representative Def.promise//if X is a promise, adopt its state [3.4]://if
          X is pending, promise must remain pending until X is fulfilled or rejected.
          If/when X is fulfilled and fulfill promise with the same value.
          If/when X is rejected, reject promise with the same reason. Newresult.then (Def, ' fulfilled '), Makesignaler (Def, ' rejected '));//The essence of this is the use of asynchronous closures} else {T
        Ransition (Def, type, newresult);
      } catch (Err) {Transition (Def, ' rejected ', err);
    } else {transition (Def, type, result);

  }
  };
    var transition = function (deferred, type, result) {if (type = = ' fulfilled ') {deferred.resolve (result);
    else if (type = = = ' rejected ') {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 (' fulfilled ', queue[i], result);
} this.promise.setStatus (' fulfilled ', 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 (' rejected ', queue[i], err);
} this.promise.setStatus (' Rejected ', err); /***************************** not read above, split line ************************************///Test Part Ajax = function (URL) {var def = n

  EW 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, does not provide error callback Def.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);//Processing data1 return Ajax (' test.php?act=2 ');}). Then (function (data2) {console.log (DATA2);//Processing data2 return Ajax (' test.php?act=3 ');}, function (err) {Console.error (
ERR);
  }). Then (function (data3) {console.log (DATA3);
Alert (' success ');
The function (err) {console.error (err);}); </script>

Php:

<?php
if ($_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));
}

Above this JavaScript promise simple learning Use method summary is small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

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.