Simple implementation of Asynchronous programming Promise mode _ basic knowledge

Source: Internet
Author: User

Asynchronous programming
JavaScript asynchronous Programming, web2.0 times more popular programming, we usually code when more or less used, the most typical is asynchronous Ajax, send 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 settimeout methods that perform callbacks asynchronously.

If you are not familiar with asynchronous programming, direct poke Ruan a Feng Daniel's tutorial, this article introduces four kinds of asynchronous programming way:

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

The maintainability of these kinds of ways increases gradually, and the difficulty of comprehension increases gradually. This summary is also aimed at the promise model.

Promise mode
So many in the way of asynchronous programming, why choose Promise, because the previous several ways inflexible, not enough to use, 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 the callback function, such as:

F1 (). then (F2);

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

In that promise mode, how the returned data is propagated among the various callback functions, you can pass the return value of a function to another function as an argument, and pass the return value of another function as a parameter to the next function, through the Resolve method ... As infinite as a "chain" to do so.

Code implementation
Implement the promise pattern by creating a promise constructor:

Constructor
var Promise = function () {
 this.callbacks = [];
}
Promise.prototype = {
 construct:promise,
 resolve:function (result) {
  this.complete (' resolve ', result);
 } ,
 reject:function (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;
 }
Test
var promise = new Promise ();
var delay1 = function () {
 settimeout (function () {
  promise.resolve (' Data 1 ');
 }, 1000);
 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: Used to manage callback functions
    • Resolve: Method to execute when a request succeeds
    • Reject: Method to execute when a request fails
    • Complete: Performing callbacks
    • Then: Binding callback function

Test:

var promise = new Promise ();
var delay1 = function () {
 settimeout (function () {
  promise.resolve (' Data 1 ');
 }, 1000);
 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 ');
 }, 1000);
 return promise;
};

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

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

Both Callback1 and Callback2 are callback functions that are 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 the then () method can be called to specify the callback function for the settimeout asynchronous execution of Delay1 (), and because the then () method also returns a Promise object. So you can call the then method again.

Step fourth
settimeout (function () {
 promise.resolve (' Data 1 ');
}, 1000);

After one second, when the other code completes, the Asynchronous Code promise.resolve (' Data 1 ') is executed, and the Resolve () method of the promise is invoked, specifying a success state and the data 1 as an argument.

Step Fifth
resolve:function (result) {
 This.complete ("resolve", result);
},
//step sixth: Loop execution callback, Passes the result of the previous callback to the next callback
complete:function (type, result) {while
 (This.callbacks[0]) {
  this.callbacks.shift () [Type] (result);
 }
,

One of the more difficult to understand is the five, six steps.

The above is the entire content of this article, I hope to help you learn.

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.