JavaScript first knowledge of promise objects

Source: Internet
Author: User

What is promise?

In fact, promise is a class, and this class has become the ES6 standard, is one of the important characteristics of ECMAScript 6 specification. This class is now supported in Chrome32, OPERA19, and Firefox29 versions, so look at es6-promise if you want to use them on all browsers.

ES6 's Promises is an implementation of the promises/a+ proposal. The various third-party implementations that you can now find, if fully compatible with promises/a+, are consistent with the ES6 Promises (of course, third-party implementations may add more APIs, and ES6 implementations need to meet the most basic requirements of the promises/a+ proposal Can). At present, of course, there are also some third-party internal libraries to implement the function, such as: Q, when, WinJS, Rsvp.js and so on.

In other words, Promise is $ in jquery. Deferred was first seen in version 1.5 as a new feature,

Why do you use Promise? The first use of 1,promise is to solve the problem of the callback black hole well.
function fn1 () {   Console.info ("This is 1");} function fn2 () {   Console.info ("This is 2");} function Fn3 () {   Console.info ("This is 3");} Call FN1 () in order, fn2 (); Fn3 ();//Output Result://this is 1//this was 2//this is 3

In fact, this does not guarantee that fn1, FN2, fn3 in order to execute. As we all know, JAVASCRITP is a single-threaded execution. Suppose

function fn1 () {  setTimeout (function () {            Console.info ("This is 1");        },5000);  }

The result is not necessarily in order. According to the asynchronous words, the back of the fn2 Fn3 must be written in F1 setimeout inside. If the complex point, it will keep nesting;

Do you want the results of the output to be executed in fn1->fn2->fn3 order?

Promise to play.
function fn1 () {          var p = new Promise ();          SetTimeout (function () {            Console.info ("This is one");            P.resolve ();          },2000);              return p;         }       function fn2 () {           var p = new Promise ();           Console.info ("This is");             P.resolve ();           return p;          }       function Fn3 () {          var p = new Promise ();          Console.info ("This is");          P.resolve ();          return p;       }  

  

The result of the output is:
This is 11
This is 22
This is 33

 

2, resolving concurrency

If we are going to show 10 records of a page, but we only have one interface that gets records through the ID, so we need to send 10 requests, and all of the requests are finished and then all of the records are added to the page, and promise is particularly suitable for use in this scenario.

IDs to get all the records of the information id//Getrecordbyid gets the logged interface and returns Promisepromise.all (Ids.map (Getrecordbyid))    . Then (showrecords)  . catch (function (e) {     console.log (e);  });

or component drop-down refresh, drop-down refresh, wait until all AJAX requests (other requests) are finished, the drop-down refresh status is completed before the refresh is turned off;

Promise.all ([Ajaxfn1, Ajaxfn2, Ajaxfn3]). Then (function (results) {    Console.log ("Success")        Console.log ( results);}). catch (function (r) {    Console.log ("err");    Console.log (R);});

  

How does Promise work?

The Promise object is used for deferred (deferred) and asynchronous (asynchronous) computations: One Promise in one of the following four states:

Pending: No positive or failure results have been achieved, in progress
Fulfilled: Successful operation
Rejected: Failed operation
Settled: has been fulfilled or rejected
The Promise object has two important methods, one is then and the other is resolve:

Then: Add the transaction to the transaction queue
Resolve: Open the process so that the entire operation starts from the first transaction

As you can see from the above figure, the Promise object has the following two characteristics.

(1) The state of the object is unaffected by the outside world. The Promise object represents an asynchronous operation in three states: Pending (in progress), resolved (completed, also known as fulfilled), and rejected (failed). Only the result of an asynchronous operation can determine which state is currently, and no other operation will change that state. This is also the origin of the name Promise, its English meaning is "commitment", that other means can not be changed.

(2) Once the state changes, it will not change, and can get this result at any time. There are only two possible changes to the state of the Promise object: from Pending to resolved and from Pending to rejected. As long as these two situations occur, the state is solidified and will not change, and will keep the result. Even if the change has occurred, you can add a callback function to the Promise object, and you will get the result immediately. This is quite different from the event, which is characterized by the event that if you miss it and then listen to it, you won't get the result.

var New Promise (functionif (/**/else  { Reject (Error); }});p Romise.then (function//  successfunction   //  failure});

The Promise constructor takes a function as a parameter, and the two parameters of the function are the Resolve method and the Reject method respectively.

If the asynchronous operation succeeds, the state of the Promise object is changed from "unfinished" to "succeeded" (that is, from pending to resolved) using the Resolve method;

If the asynchronous operation fails, The Reject method is used to change the state of the Promise object from "Unfinished" to "failed" (that is, from pending to rejected).

The basic API
    1. Promise.resolve ()//success
    2. Promise.reject ()//failure
    3. Promise.prototype.then ()
    4. Promise.prototype.catch ()
    5. Promise.all ()//all completed
    6. Promise.race ()//racing, complete one can
How is Promise implemented?

The general framework principle is as follows

var Promise = function () {    this.callbacks = [];} Promise.prototype = {    constructor: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);        }    } and then    : function (Successhandler, failedhandler) {        This.callbacks.push ({            resolve:successhandler,            reject: Failedhandler        });        return this;    }}

Test code

TestVar 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);

In practice, this is not enough for the production environment;

reference documents;

How to implement Promise http://liuwanlin.info/shi-xian-promise/
The artifact in Javascript--promise http://www.jianshu.com/p/063f7e490e9a
Recommended Primise plug-in https://github.com/stefanpenner/es6-promise
Recommend this article https://www.promisejs.org/implementing/
The analysis of the American Regiment Promise the foundation of http://tech.meituan.com/promise-insight.html
promises/a+ https://promisesaplus.com/
Mdn-promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

JavaScript first knowledge of promise objects

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.