Simple asynchronous programming promise mode and asynchronous promise Mode

Source: Internet
Author: User

Simple asynchronous programming promise mode and asynchronous promise Mode

Asynchronous programming
Javascript asynchronous programming: popular programming methods in the web2.0 era. We usually use code more or less. The most typical is asynchronous ajax, which sends asynchronous requests and binds callback functions, after the request is responded, the specified callback function is called without blocking the execution of other code. The setTimeout method is also used for asynchronous callback execution.

If you are not familiar with asynchronous programming, you can directly peat the tutorial of Ruan Yifeng. This article introduces four asynchronous programming methods:

  1. Callback Function
  2. Event listening
  3. Publish/Subscribe
  4. Promise Mode

The maintainability of these methods increases step by step, and the difficulty of understanding also increases step by step. This summary is also for the promise mode.

Promise Mode
So many asynchronous programming methods, why choose promise, because the previous methods are not flexible enough to use, not good enough, not elegant. To reduce the complexity of asynchronous programming, promise.

The core of promise is a promise object, which has an important then () method used to specify callback functions, such:

f1().then(f2);

The promise mode has three statuses at any time: completed (resolved) and unfulfilled (unfulfilled). then, the then () method specifies different callback functions for state changes, always Returns a promise object to facilitate chained calls.

In promise mode, how does the returned data spread between various callback functions? Using the resolve method, you can pass the return value of a function as a parameter to another function, and pass the return value of another function as a parameter to the next function ...... Do this infinitely like a chain.

Code Implementation
Create a Promise constructor to implement the promise mode:

// Constructorvar 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 ;}// testvar 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 the constructor of a simple promise object:

  • Callbacks: used to manage callback Functions
  • Resolve: method executed when the request is successful
  • Reject: method executed when the request fails
  • Complete: Execution callback
  • Then: bind the 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 );

Result:

Output after one second:

Analysis:

// Step 1 var delay1 = function () {setTimeout (function () {promise. resolve ('data 1') ;}, 1000); return promise ;};

This function uses the setTimeout method to asynchronously pass a data 1 and return a promise object (required ).

// Step 2 var callback1 = function (re) {re = re + 'data 2'; console. log (re); promise. resolve (re );};

Both callback1 and callback2 are callback functions to be registered using the then method. callback1 uses the resolve Method to pass data down.

// Step 3 delay1 (). then (callback1). then (callback2 );

After the delay1 () method is executed, because a promise object is returned, you can call the setTimeout asynchronous execution of the then () method as delay1 () to specify the callback function () the method also returns the promise object, so you can call the then method again.

// Step 4: setTimeout (function () {promise. resolve ('data 1');}, 1000 );

One second later, when other code execution is complete, the asynchronous code promise will be executed. resolve ('data 1'); here, the resolve () method of promise is called, a success state is specified, and data 1 is taken as the parameter.

// Step 5 resolve: function (result) {this. complete ("resolve", result) ;}, // Step 6: Execute the callback in a loop 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 );}},

The fifth and sixth steps are hard to understand.

The above is all the content of this article, hoping to help you learn.

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.