Blue Bird Bluebird Promise Library Introduction

Source: Internet
Author: User

In small program development, the use of promise can significantly reduce the code, improve the simplicity of the code. The following article from the blog Park Lu Tai Leopard vernacular explain promise, the article written very well, concise and understandable, it is worth reading. The transcript is reproduced here, with a slight partial deletion.

This library is in the browser and is common in small programs. There are four main uses: use then to implement chained calls: sequentially complete the serial task, the previous task as the next task's condition and basis for parallel invocation using Promise.all, subtasks complete as complete, there is no dependency between these subtasks Use Promise.race to implement contest calls, as long as a complete is considered complete, for example, in the case of Ping server, select one of the fastest servers to use catch to catch abnormal conditions, including exceptions and return unexpected results

Last June, ES2015 officially released (that is, Es6,es6 was its nickname), Promise was listed as a formal norm. As one of the most important characteristics of ES6, it is necessary to grasp and understand it thoroughly. This article will be from shallow to deep, explain the basic concept of promise and use methods. about ES6 Promise

The complex concept is not to speak first, we first simply rough to use promise, have an intuitive feeling. So the first question comes, what is promise.

Print it out and look at it, Console.dir (Promise):

So see, Promise is a constructor, oneself body has all, reject, resolve these several familiar methods, the prototype has then, catch and so on the same very familiar method. So the object that uses promise new comes out must have then, catch method, right.


Let's play a new game.

var p = new Promise (function (resolve, reject) {
    //Do some asynchronous operations
    settimeout (function () {
        console.log (' execution completed ');
        Resolve (' random data ');
    };

The promise constructor receives a parameter, is a function, and passes in two arguments: Resolve,reject, respectively, representing the callback function after the successful execution of the asynchronous operation and the failure of the asynchronous operation. In fact, here with "success" and "failure" to describe the inaccurate, according to the standard, resolve is the state of promise to Fullfiled,reject is the promise state to rejected. But at the beginning we can understand this first, and then examine the concept later.


In the above code, we performed an asynchronous operation, that is, after settimeout,2 seconds, the output "execution complete" and the Resolve method is invoked.


Running the code will output "execution complete" in 2 seconds. Attention. I was just new to an object and didn't call it, and the function we passed in was already executed, which is a detail to note. So when we use promise, it's usually wrapped in a function that runs this function when needed, such as:

function Runasync () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operations
        settimeout (function () {
            console.log (' execution completed ');
            Resolve (' random data ');
        };
    return p;            
}
Runasync ()


At this point you should have two questions: 1. Packing such a function is used for wool. 2.resolve (' random data '); it's dry hair.


Let's continue. At the end of our wrapped function, we return the Promise object, which means that we get a promise object to execute this function. Remember that there are then, catch methods on the Promise object. That's where the power is, look at the following code:

Runasync (). Then (function (data) {
    console.log (data);
    The following can be used to do some other operation of the data
    //...
};


The then method is called directly on the return of Runasync (), then receives a parameter, is a function, and gets the arguments we call resolve newsletters in Runasync. Running this code will output "execution complete" in 2 seconds, followed by the output "random data."


At this time you should have understood, the original then inside function and our usual callback function a meaning, can be executed after runasync this asynchronous task execution completes. This is the role of promise, in simple terms, is to be able to separate the original callback writing, in the asynchronous operation, after the execution of a chain call to execute the callback function.


You may be dismissive, so the promise is capable. I encapsulate the callback function, and it's not the same for Runasync, like this:


function Runasync (callback) {
    settimeout (function () {
        console.log (' execution completed ');
        Callback (' random data ');
    }

Runasync (function (data) {
    console.log (data);
});


The effect is the same, but also the difficulty of doing with promise. So here's the question, how about having multiple callbacks? What if callback is also an asynchronous operation and needs to have the corresponding callback function after the execution. You can never define a callback2, and then pass it on to callback. The advantage of promise is that you can continue to write the Promise object in the then method and return it, and then continue calling then for the callback operation. use of chained operations

So, on the surface, promise just can simplify the writing of the layer callback, and in essence, the essence of Promise is "state", with the maintenance state, the way of passing state to make callback function can be called in time, it is more simple and flexible than passing the callback function. 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 allows the contents of each asynchronous callback to be output in sequence, every two seconds, and passed to resolve data in the RUNASYNC2, which can be obtained in the next then method. The results of the operation are as follows:

Guess how the three functions of runAsync1, RUNASYNC2, and runAsync3 are defined. That's right, that's it. (Longer code, please expand yourself):

function RunAsync1 () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operations
        settimeout (function () {
            Console.log (' Asynchronous task 1 execution completed ');
            Resolve (' Random data 1 ');
        }, 1000);
    };
    return p;            
}
function RunAsync2 () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operations
        settimeout (function () {
            Console.log (' Asynchronous Task 2 execution completed ');
            Resolve (' Random data 2 ');
        };
    return p;            
}
function runAsync3 () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operations
        settimeout (function () {
            Console.log (' Asynchronous task 3 execution completed ');
            Resolve (' Random data 3 ');
        };
    return p;            
}

In the then method, you can return the data directly instead of the Promise object, and you can receive the data in the following then, for example, we modify the above code like this:


RUNASYNC1 ()
. Then (function (data) {
    console.log (data);
    return RunAsync2 ();
})
. Then (function (data) {
    console.log (data);
    Return ' direct data ';  Here directly returns data
})
. Then (function (data) {
    console.log (data);
});


Then the output becomes this: the use of Reject

Here, you should have a basic understanding of what "promise" is. So let's take a look at ES6 's promise. We use the resolve, still do not use reject, what is it to do? In fact, the previous examples are all only "successful" callbacks, there is no "failure" situation, the role of reject is to put the state of promise to rejected, so that we can capture in the then, and then perform a "failed" callback. Look at the code below.

function GetNumber () {
    var p = new Promise (function (resolve, reject) {
        //Do some asynchronous operations
        settimeout (function () {
            var num = Math.ceil (math.random () *10);//Generate 1-10 random number
            if (num<=5) {
                resolve (num);
            }
            else{
                reject (' number too large ');
    }}; return p;            
}

GetNumber ()
. Then (
    function (data) {
        Console.log (' resolved ');
        Console.log (data);
    }, 
    function (reason, data) {
        console.log (' rejected ');
        Console.log (reason);
    }
);


The GetNumber function is used to get a number asynchronously, 2 seconds to execute, and if the number is less than 5, we think it is "successful", and call resolve modify the Promise state. Otherwise we think it is "failed", call reject and pass a parameter as the cause of the failure.


Running GetNumber and passing two parameters in then, the then method can accept two parameters, the first corresponding to the resolve callback, and the second to the reject callback. So we were able to get the data that they had handed over. Run this code multiple times, and you'll randomly get the following two kinds of results:

Or

Use of Catch

We know that the Promise object has a catch method in addition to the then method, what does it do? In fact, it is the same as the second parameter of then, which specifies the callback of the Reject, which is used:

GetNumber ()
. Then (function (data) {
    Console.log (' resolved ');
    Console.log (data);
})
. catch (function (reason) {
    console.log (' rejected ');
    Console.log (reason);
});

The effect is the same as the second argument written in then. But it has another effect: when performing a resolve callback (i.e. the first argument in the then above), if the exception is thrown (the code is wrong), then the error will not be stuck JS, but will go into the catch method. Take a look at the following code:

GetNumber ()
. Then (function (data) {
    Console.log (' resolved ');
    Console.log (data);
    Console.log (Somedata); Somedata not defined here
})
. catch (function (reason) {
    console.log (' rejected ');
    Console.log (reason);
});

In the resolve callback, we Console.log (Somedata), and somedata this variable is not defined. If we do not promise, the code to run here directly in the console error, do not run down. But here, you get the result:

That means going into the catch method, and uploading the wrong reason to the reason parameter. Even the wrong code does not complain, which is the same function as our Try/catch statement. Use of all

The Promise all method provides the ability to perform asynchronous operations in parallel and performs callbacks after all asynchronous operations have been executed. We still use the three functions defined above runAsync1, RUNASYNC2, runAsync3 to see the following example:

Promise
. All ([RunAsync1 (), RunAsync2 (), runAsync3 ()])
. Then (function (results) {
    console.log (results);
});


Executes with Promise.all, all receives an array parameter, the value of which is eventually returned to the Promise object. In this way, three asynchronous operations are executed in parallel until they are executed before they are entered into the then. So, where are the data returned by three asynchronous operations? All in then, all will put the results of all the asynchronous operations into an array of then, which is the results above. So the output of the above code is:


With all, you can perform multiple asynchronous operations in parallel, and it's cool to handle all the return data in a callback. There is a scene is very suitable for this, some game class material more application, open the page, preload need to use a variety of resources such as pictures, Flash and a variety of static files. After all of the loading, we do the initialization of the page. the use of race

The effect of the all method is actually "who runs slowly, who is to perform the callback", then there is another method of "who runs fast, who is to perform the callback", this is the race method, the word is originally the meaning of the race. Race's usage is the same as all, we change the above runAsync1 delay to 1 seconds to see:

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.