Simple implementation of asynchronous programming promise mode

Source: Internet
Author: User

This article mainly introduces the asynchronous programming promise mode simple realization, and carries on the analysis to each step, the need friend can refer to the next

Asynchronous programming
JavaScript asynchronous programming, the web2.0 era of popular programming, we usually use the code, the most typical is asynchronous Ajax, send an asynchronous request, binding callback function, request response after calling the specified callback function, not blocking the execution of other code. There are also methods like the SetTimeout method that perform callbacks asynchronously.

If you are not familiar with asynchronous programming, directly poke Ruan-Feng's tutorial, this article describes the four ways of asynchronous programming:

    1. callback function
    2. Event Monitoring
    3. Publish/Subscribe
    4. Promise mode

The maintainability of these methods increases gradually, and the difficulty of comprehension is gradually increasing. This summary is also for the promise model.

Promise mode
So much in the way of asynchronous programming, why choose Promise, because the previous ways are not flexible enough to use not happy, not elegant. To reduce the complexity of asynchronous programming, promise.

The core of promise is a promise object that has an important then () method that specifies a callback function, such as:

F1 (). then (F2);

Promise mode has three states at any time: Completed (resolved), incomplete (unfulfilled), then the then () method specifies a different callback function for state changes, and always returns a promise object for easy chaining.

In that promise mode, how does the returned data propagate between the various callback functions, through the Resolve method, you can pass the return value of one function as an argument to another function, and pass the return value of another function as a parameter to the next function ... Like a "chain" to do so indefinitely.

Code implementation
Implement promise mode by creating a promise constructor:

Constructorvar Promise = function () {this.callbacks = [];} Promise.prototype = {construct:promise, resolve:function (result) {  This.complete ("resolve", result);}, Reject:fu Nction (Result) {  this.complete ("reject", result),}, Complete:function (type, result) {while  (this.callbacks[ 0]) {   this.callbacks.shift () [type] (result);  }, Then:function (Successhandler, Failedhandler) {  This.callbacks.push ({   resolve:successhandler,   reject:failedhandler  });  return this; }}//TestVar promise = new Promise (), var delay1 = function () {setTimeout (function () {  promise.resolve (' Data 1 ');}, 100 0); return promise;}; var callback1 = function (re) {re = re + ' data 2 '; Console.log (re);}; Delay1 (). Then (CALLBACK1)

  

Code Analysis
We can see the structure of a simple promise object's constructor:

    • Callbacks: for managing callback functions
    • Resolve: Method to execute when the request succeeds
    • Reject: Method to execute when a request fails
    • Complete: Execution callback
    • Then: Bind callback function

Test:

var promise = new Promise (), var delay1 = function () {setTimeout (function () {  promise.resolve (' Data 1 ');}, +); return Promise;}; var callback1 = function (re) {re = re + ' data 2 '; Console.log (re); Promise.resolve (re);}; var callback2 = function (re) {Console.log (re + ' data 3 ');}; Delay1 (). Then (CALLBACK1). then (CALLBACK2);

Results:

Output after one second:

Analysis:

The first step is var delay1 = function () {setTimeout (function () {  promise.resolve (' Data 1 ');}, +); return promise;};

This function asynchronously passes a data 1 through the SetTimeout method, and returns a Promise object (must).

The second step is var callback1 = function (re) {   re = re + ' data 2 '; Console.log (re); Promise.resolve (re);};

Both Callback1 and Callback2 are callback functions to be registered through the then method, where Callback1 passes the data down through the Resolve method.

Step three Delay1 (). Then (CALLBACK1). then (CALLBACK2);

  

The Delay1 () method finishes executing because a Promise object is returned, so you can call the then () method to specify the callback function for the settimeout asynchronous execution of Delay1 (), and because the then () method also returns the Promise object. So you can call the then method again.

Fourth Step settimeout (function () {promise.resolve (' data 1 ');}, 1000);

After one second, when the other code finishes executing, the asynchronous Code promise.resolve (' Data 1 ') starts executing, and here the Promise resolve () method is called, specifying a success state and data 1 as the parameter.

Fifth Step resolve:function (Result) {This.complete ("resolve", result),},//Sixth step: Loop through the callback and pass the result of the previous callback to the next callback complete: function (type, result) {while (This.callbacks[0]) {  this.callbacks.shift () [type] (result);},

This is more difficult to understand is the five, six steps.

The above is the whole content of this article, I hope that everyone's study has helped.

Turn from (http://www.jb51.net/article/70447.htm)

Simple implementation of asynchronous programming promise mode

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.