Brief analysis of ES6 Promise

Source: Internet
Author: User
1. A preliminary understanding of promise from a macroscopic perspective

Promise meaning is not the literal "oath" or "promise", but the meaning of "prophet".

Although human behavior can be parallel, conscious thinking activities show a single-threaded nature.

For example, ordinary people can only think of one problem at a time. In the process of thinking, it is sometimes suddenly inspired by inspiration to associate with other problems.

people who are familiar with JavaScript may already realize:

There are many similarities between the thought process of human conscious level and the execution process of JS.

JS executes along the timeline, in which a timer or callback is inserted. Time is the axis of the process.

JS Creator may be in order to be as simple as possible with the human mind to fit together, will be so designed JS this language.

However, the real world is complex, and the problems that JS needs to deal with are complex.

In the real world, as an ordinary person, thinking with the time of this dimension, always do a single-threaded operation. The parameters of the operation are the sum of the information that "every moment" can get.

Ordinary people are relatively "comfortable", if the human and the environment are "God" written procedures, then this "God" is not so "comfortable". Because, "he" needs to be pre-considered in each scenario, each of the various possible evolution.

As a programmer, for the written program, to some extent, the role of "God". (see here, is not a bit of a feeling of being smug)

But we do not have the ability, our thinking is still single-threaded. Accidentally fell into the "callback Hell".

At this point we need an artifact that gives us the ability to be "prophetic" . Promise is the representative of this kind of artifact.


2. What is Promise

Promise is a solution for asynchronous programming that is more logical and powerful than traditional solutions-callback functions and events. It was first proposed and implemented by the community, ES6 wrote it into the language standard, unified the usage, the native provided the Promise object.

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 (rejected). Only the result of an asynchronous operation can determine which state is currently, and no other operation will change the state

(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.

For more promise specifications, please refer to the http://malcolmyu.github.io/malnote/2015/06/12/Promises-A-Plus/


3. The Promise in ES6

Print out the Promise at the console first, Console.dir (Promise)



From the above figure, promise is a function, the body has all, race, reject, resolve and other methods, the prototype has then, catch and other methods

ES6 specifies that the Promise object is a constructor used to generate the promise instance.

Creates a promise instance:

var p = new Promise (function (resolve, reject) {
    //Do some asynchronous operation
    SetTimeout (function () {
        console.log (' execution complete ');
        var num = Math.random ();
        if (num>=0.5) {
            resolve (num);
        } else{
            reject (' number is less than 0.5 ');}
       
    }
;

Promise will be executed immediately after the new build.

In the above code, a timer that executes after a 2s is set.

After 2s output "execute complete", then generate a random number, if the number is greater than or equal to 0.5, we think is "successful", call resolve modify the state of promise. Otherwise we think it is "failed", call reject and pass a parameter as the cause of "failure".


The purpose of the Resolve function is to change the state of the Promise object from "unfinished" to "resolved" (that is, from pending to resolved), to invoke when the asynchronous operation succeeds, and to pass the result of the asynchronous operation as a parameter;

The purpose of the Reject function is to change the state of the Promise object from "unfinished" to "deny" (that is, from pending to rejected), to invoke when an asynchronous operation fails, and to pass an error reported by an asynchronous operation as a parameter.


4. Examples of use of promise

The following is an example of loading a picture asynchronously.

function Loadimageasync (URL) {
  return new Promise (function (resolve, reject) {
    var image = new Image ();

    Image.onload = function () {
      resolve (image);
    };

    Image.onerror = function () {
      reject (new Error (' Could not load image at ' + URL)};

    image.src = URL;
  });
}

In the above code, an asynchronous operation with a picture loaded is wrapped using promise. If the load succeeds, the Resolve method is called, otherwise the Reject method is called.


Promise.prototype.then ()

The first parameter of the then method is the callback function for the resolved state, and the second argument (optional) is the callback function for the rejected state.

On the surface, promise just simplifies the writing of the layer callback, and in essence, the essence of Promise is "state", so that the callback function can be called in time by maintaining state and transmitting State, it is more simple and flexible than passing callback function.

function RunAsync1 () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operation
        SetTimeout (function () {
            console.log (' execution completed 1 ');
            Resolve (' data 1 ');}
    );
    return p;            
}

function RunAsync2 () {
    var p = new Promise (function (resolve, reject) {
        setTimeout (function () {
            Console.log (' execution completed 2 ');
            Resolve (' Data 2 ');}
    );
    return p;            
}

function runAsync3 () {
    var p = new Promise (function (resolve, reject) {
        setTimeout (function () {
            Console.log (' execution completed 3 ');
            Resolve (' Data 3 ');}
    );
    return p;            
}

The chained call code is as follows:

RUNASYNC1 ()
. Then (function (data) {
    console.log (data);
    return RunAsync2 ();
})
. Then (the function (data) {
    console.log (data);
    return runAsync3 ();
})
. Then (function (data) {
    console.log (data);
});
The output of the above code is:

Execution Complete 1

Data 1

Execution Completion 2 Data 2

Execution Complete 3

Data 3


Promise.prototype.catch ()

The Promise.prototype.catch method is an alias for. Then (null, rejection), which specifies the callback function when an error occurs.

var promise = new Promise (function (resolve, reject) {
  throw new Error (' Test ');
});
Promise.catch (function (Error) {
  console.log (error);
});
In the above code, promise throws an error that is captured by the callback function specified by the Catch method.

It is important to note that the Catch method returns a Promise object, so you can then call the then method later.

var someasyncthing = function () {
  return new Promise (function (resolve, reject) {
    ///The following line will be an error because X is not declared
    resolve (x + 2)

;}; Someasyncthing ()
. catch (function (error) {
  console.log (' Oh no ', error);
})
. Then (function () {
  console.log (' Carry On ');
});
Oh no [referenceerror:x isn't defined]
//Carry On
The above code runs through the callback function specified by the Catch method and then runs the callback function specified by the subsequent then method. If there is no error, the Catch method is skipped.


Promise.all ()

The Promise.all method is used to wrap multiple Promise instances into a new Promise instance.

Here is an example where runAsync1, RunAsync1, and runAsync3 are already defined in the example above

Promise
. All ([RunAsync1 (), RunAsync2 (), runAsync3 ()])
. Then (function (results) {
    Console.log ( results);
});
The output of the above code is:

Execution Complete 1

Execution Complete 2

Execution Complete 3

["Data 1", "Data 2", "Data 3"]

With all, you can execute multiple asynchronous operations in parallel and process all return data in a callback.


Promise.race ()

The Promise.race method also wraps multiple Promise instances into a new Promise instance.

The effect of the all method is actually "who runs slowly, who is the quasi-callback", then there is another way to race"who runs fast, who will be the quasi-execution callback".

Let's change the delay of the above runAsync1 to 1 seconds to see:

Promise
. Race ([RunAsync1 (), RunAsync2 (), runAsync3 ()])
. Then (function (results) {
    Console.log (results) ;
});
The output of the above code is:

Execution Complete 1

Data 1

Execution Complete 2

Execution Completion 3 When the callback in then starts executing, RUNASYNC2 () and runAsync3 () do not stop and continue. Then after 1 seconds, they output the sign of their end.

What's the use of this race? The use of the scene is still a lot, for example, we can use race to set the timeout time for an asynchronous request, and after the timeout, the corresponding operation, the code is as follows:

Request a picture resource
function requestimg () {
    var p = new Promise (function (resolve, reject) {
        var img = new Image ();
        Img.onload = function () {
            resolve (IMG);
        }
        IMG.SRC = ' xxxxxx ';
    });
    return p;
}

The delay function, which is used to give the request a timer functions
timeout () {
    var p = new Promise (function (resolve, reject) {
        setTimeout (function () {
            reject (' Picture request timed out ');
        }
    )
    ; return p;
}

Promise
. Race ([Requestimg (), timeout ()])
. Then (function (results) {
    console.log (results);
})
. catch (function (reason) {
    console.log (reason);
});
The REQUESTIMG function asynchronously requests a picture, I write the address as "xxxxxx", so it must not be successfully requested. The timeout function is an asynchronous operation with a delay of 5 seconds. We put the two functions returned to the Promise object into the race, so they will race, if the picture request is successful within 5 seconds, then go through the then method to perform the normal process. If the 5-second picture has not been successfully returned, then timeout will win, then go to catch and quote "Picture Request timed out" information.

Supplement

The above code examples are derived from the network.

Main articles of reference:

http://malcolmyu.github.io/malnote/2015/06/12/Promises-A-Plus/

Http://www.cnblogs.com/lvdabao/p/es6-promise-1.html

http://www.zhangxinxu.com/wordpress/2014/02/es6-javascript-promise-%E6%84%9F%E6%80%A7%E8%AE%A4%E7%9F%A5/

http://es6.ruanyifeng.com/#docs/promise

https://segmentfault.com/a/1190000000684654


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.