You don't know the Javascript--item34 plain English commentary promise

Source: Internet
Author: User
Tags lua

Last June. ES2015 officially announced (aka ES6. ES6 is its nickname), in which promise is classified as a formal norm. As one of the most important features of ES6, we need to master and understand it thoroughly. This article will be from shallow to deep, explain the basic concept of promise and use method.

ES6 Promise first pull out for a walk

First, promise small test

The concept of complexity first, we first simple rough promise to use, there is an intuitive feeling.

So the first question comes. What the hell is promise? is a class? Object? Array? Function?

Don't guess, just print it out and check it out. Console.dir (Promise), it's so simple and rude.

That's a clear look. Promise is a constructor, the body has all, reject, resolve these familiar methods, the prototype has then, catch and so on the same very familiar method. So there must be a then and catch method for the promise new object, yes.

Let's play a new game.

varnew Promise(function(resolve, reject){        //做一些异步操作    setTimeout(function(){        console.log(‘运行完毕‘);        resolve(‘随便什么数据‘);    2000);});

The promise constructor receives a parameter, is a function, and passes in two parameters: Resolve,reject. Represents the callback function after the successful operation of the asynchronous operation and the callback function after the asynchronous operation failed to run. In fact, the description of "success" and "failure" to describe the narrative is not accurate, according to the standard, resolve is to promise the state of Fullfiled,reject is to set the promise state as rejected. It is only at the beginning of the stage that we can understand this, and then scrutiny the concept behind.

In the code above, we ran an asynchronous operation, that is, settimeout,2 seconds later. The output is "finished running." and call the Resolve method.

The

Runs the code and outputs "Run complete" in 2 seconds. Note! I was just a new object and didn't call it, and the function we passed in was already running. This is a detail that needs attention. So when we use promise, we usually wrap it in a function, and run the function when it's needed, such as:

function runAsync(){        varnew Promise(function(resolve, reject){            //做一些异步操作    setTimeout(function(){            console.log(‘运行完毕‘);            resolve(‘随便什么数据‘);        2000);    });        return p;            }runAsync()

At this point you should have two questions:

    • 1. Packing such a function for yarn use?
    • 2.resolve (' random data '); This is dry hair?

We're going to keep speaking. At the end of our packaged function. will return the Promise object. That is, to run this function we get a promise object. Remember the Promise object has then, catch method? This is where the power is, look at the following code:

runAsync().then(function(data){    console.log(data);        //后面能够用传过来的数据做些其它操作    //......});

Call the then method directly on the return of Runasync (), then receive a parameter, which is the function, and get the number of the runasync that we call resolve simultaneous. Running this code will output "run complete" after 2 seconds, followed by the output "whatever data".

Ii. Explanation of key methods What the hell is 2.1 then?

At this point you should be able to understand, the original then inside the function with our usual callback function one meaning. Can be run after Runasync this asynchronous task has finished running.

This is the role of promise, simply speaking. is to be able to separate the original callback method, after the asynchronous operation is finished running, the callback function is run in a chained call.

You might be dismissive, so what's the promise? I encapsulate the callback function. It's not the same for Runasync, just like this:

function runAsync(callback){    setTimeout(function(){        console.log(‘运行完毕‘);        callback(‘随便什么数据‘);    2000);}runAsync(function(data){    console.log(data);});

The effect is the same, but also hard to do with promise.

So the question is, what should I do with multiple levels of callbacks? Suppose callback is also an asynchronous operation, and it needs a corresponding callback function after running, what should I do? There is no longer a callback2 to define. Then pass it on to callback. And the advantage of promise is that. The Promise object can continue to be written and returned in the then method, and then continue to invoke then to perform the callback operation.

2.2 How to use chain operation

So, on the face of it, promise is simply the ability to simplify the writing of layers of callbacks, but in essence. The essence of Promise is "state", which allows callback functions to be called in a timely manner by maintaining state and passing state. It is much simpler and more flexible than passing callback functions. so the correct scenario for using promise is this:

runAsync1().then(function(data){    console.log(data);        return runAsync2();}).then(function(data){    console.log(data);        return runAsync3();}).then(function(data){    console.log(data);});

This enables the output of the contents of each asynchronous callback in sequence, every two seconds, and the data passed to resolve in RunAsync2, which can be obtained in the next and then method. Running results such as the following:

Guess how the three functions of RunAsync1, RUNASYNC2, runAsync3 are defined? Yes, it is the following:

 function runAsync1(){        varp =NewPromise ( function(resolve, Reject){        //Do some asynchronous operationsSetTimeout ( function(){Console.log (' Asynchronous Task 1 is complete '); Resolve' Whatever data 1 '); }, +); });returnP } function runAsync2(){        varp =NewPromise ( function(resolve, Reject){        //Do some asynchronous operationsSetTimeout ( function(){Console.log (' Asynchronous Task 2 is complete '); Resolve' Whatever data 2 '); }, -); });returnP } function runAsync3(){        varp =NewPromise ( function(resolve, Reject){        //Do some asynchronous operationsSetTimeout ( function(){Console.log (' Asynchronous Task 3 is complete '); Resolve' Whatever data 3 '); }, -); });returnP }

In the then method. You can also return directly to the data instead of the Promise object, then you can receive the data in the later, for example, we changed the code above to:

runAsync1().then(function(data){    console.log(data);    return runAsync2();}).then(function(data){    console.log(data);    return‘直接返回数据‘//这里直接返回数据.then(function(data){    console.log(data);});

Then the output becomes this:

How to use 2.3 Reject

Here, you should have the most important understanding of what "promise is". So let's take a look at ES6 's promise.

We used the resolve for light. It's useless reject, what does it do? In fact, our previous example is just a "run success" callback, there is no "failure" situation, reject's role is to put the promise state as rejected, so that we can capture in then, and then run the "failure" condition of the callback. Look at the following code.

 function getnumber(){        varp =NewPromise ( function(resolve, Reject){           //Do some asynchronous operationsSetTimeout ( function(){                        varnum =Math. Ceil (Math. Random () *Ten);//Generate 1-10 of random numbers            if(num<=5) {resolve (num); }Else{Reject (' The numbers are too big '); }        }, -); });returnP }
getnumber () then (function   { console.  log         ( ' resolved ' ); console.  log     (data); }, function   (reason, data  { console.  log         ( ' rejected ' ); console.  log     (reason); });

The GetNumber function is used to asynchronously get a number. After 2 seconds, the operation is complete. Assuming that the number is less than or equal to 5, we feel "successful" and call resolve to change the state of promise . Otherwise we think it is "failed", call reject and pass a number of parameters. As a cause of failure.

Runs GetNumber and then passes two parameters, then the then method can accept two parameters. callback for the first corresponding resolve. A callback for the second corresponding reject .

So we were able to get the data they sent. Run this code multiple times. You will randomly get the following two results:

Or

How to use 2.4 catch

We know that the Promise object is in addition to the then method and another catch method. What is it used for? In fact, it's the same as the second one. Used to specify a callback for reject , using this method:

getnumber () then (function   { console.  log     ( ' resolved ' ); console.  log  (data);}). catch  (function   (reason)  { console.  log     ( ' rejected ' ); console.  log  (reason);});  

The effect is the same as the second parameter written in then. But it has another function: when running the resolve callback (that is, the first parameter in the top then), assuming that the exception is thrown (the code is wrong), then the error will not die JS, but into the catch method.

Take a look at the following code:

getNumber().then(function(data){    console.log(‘resolved‘);    console.log(data);    console//此处的somedata没有定义.catch(function(reason){    console.log(‘rejected‘);    console.log(reason);});

In Resolve's callback, we Console.log (Somedata), and somedata this variable is undefined. Let's say we don't have to promise, the code runs here and it goes straight to the console. Don't run down.

But here, you get this result:

That is to go to the catch method inside, and the wrong reason passed to the reason parameters.

Even the wrong code will not get an error, which has the same function as our Try/catch statement.

How to use 2.5 all

The Promise all method provides the ability to run asynchronous operations in parallel. And the callback is not run until all asynchronous operations have finished running. We still use the three functions defined above, RUNASYNC1, RunAsync2, and runAsync3, to see the following examples:

Promise.all([runAsync1(), runAsync2(), runAsync3()]).then(function(results){    console.log(results);});

Run with Promise.all. All receives an array of parameters, and the value is finally returned to the Promise object. In this way, three asynchronous operations run in parallel until they are all running and then go inside.

So. What happened to the data returned by three asynchronous operations? All in the then, all will put the results of all asynchronous operations into an array and pass it to then, which is the results above. So the output from the above code is:

With all. You can run multiple asynchronous operations in parallel and process all return data in a callback. Isn't it really cool? There is a scene that is very suitable for use with this, some of the game classes of material more than the application, when opening the Web page. Pre-loaded with all kinds of resource slices, flash, and various static files that need to be used.

All of them are loaded and finished. Let's do the initialization of the page again.

How to use 2.6 race

The effect of the all method is actually "who runs slowly, and who is the quasi-run callback". Then there is another way of "who runs Fast and who will run the callback". This is the race method, the word is meant to race. Race using the same method as all, we change the delay of the above runAsync1 to 1 seconds to see:

Promise.race([runAsync1(), runAsync2(), runAsync3()]).then(function(results){    console.log(results);});

The same three asynchronous operations are run in parallel. As a result you should be able to guess that after 1 seconds the RUNASYNC1 has run out, and then the inside is running.

The result is this:

Have you guessed it right? Not totally, is it. RunAsync2 () and runAsync3 () do not stop when the callbacks in then start to run. Still running again. 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 very much, for example, we can use race to set the timeout time for an asynchronous request, and then run the appropriate operation after the timeout . The code is as follows:

//Request a picture resource function requestimg(){        varp =NewPromise ( function(resolve, Reject){                    varIMG =NewImage (); Img.onload = function(){Resolve (IMG); } IMG.SRC =' xxxxxx '; });returnP;}//Delay function. Used to timing a request function timeout(){      varp =NewPromise ( function(resolve, Reject){SetTimeout ( function(){Reject' picture request timed out '); }, the); });returnP;}
Promise.race([requestImg(), timeout()]).then(function(results){    console.log(results);}).catch(function(reason){    console.log(reason);});

The REQUESTIMG function asynchronously requests a picture, and I write the address as "xxxxxx". So there must be no successful request.

The timeout function is an asynchronous operation with a delay of 5 seconds.

We put the two functions that returned to the promise object into the race, so that they would race. Assuming that the picture request succeeds within 5 seconds, then go through the then method and run the normal process. Assuming that the 5-second picture has not been successfully returned, then timeout will win, then go to catch and quote "Picture Request timed out" information. Running results such as the following:

Iii. Summary

Is that what ES6 promise? Yes. That's the basic stuff you can use.
How come I've seen done, finally, success, fail and so on, what are these? These are not in the promise standard, but in the grammatical sugars we implement ourselves.

All of the asynchronous operations in this article take settimeout as a sample, and the reason for not using Ajax is to avoid confusion. Since talking about Ajax, a lot of people's first reaction is jquery Ajax, and jquery has its own promise implementation.

Assuming you understand the principle, you know that using settimeout is the same as using Ajax.

Speaking of jquery, I have to spit out a groove, jquery promise to achieve too much rubbish, all kinds of grammatical sugar people are cast, I think promise the reason is not comprehensive and jquery has a very big relationship. We'll talk about jquery in the back.

You don't know the Javascript--item34 plain English commentary promise

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.