ES6 (1)-promise Study

Source: Internet
Author: User

Anyone who learns Android knows that Java is multi-threaded, and when it takes a time-consuming operation, such as requesting data from the server, it is often necessary to open a thread to execute it.
But in our JS, is single-threaded, request network data, we can not determine when will return, if the network is not very good, then it will be very slow. So it is impossible to wait for his request to complete before going to the next steps. So we need to ask for the data asynchronously, but we need to know the result of the request, and then we need an interface callback to tell us the result of the request.

In ES6, promise is provided for asynchronous operations and callbacks are implemented.
Use the following:

var promise = new Promise (function (resolve, reject) {
            //perform some asynchronous or time-consuming operations
            if (1) {
                //condition is met, asynchronous operation succeeds
                resolve (" Success! ");
            } else {
                //condition does not satisfy
                reject ("fail");
            }
        });
        The binding handler
        Promise.then (function (result) {
            //promise succeeded callback
            console.log (result);//"Success"
        }, function (err) {
            //promise failed callback
            Console.log (ERR);//Error: "Fail"
        });

The

is implemented in three steps:
1. The first step: Create a Promise object and do something in it, such as AJAX request Data
2. Step two: In this object method, specify the condition accordingly. For example, when the AJAX request returns the data state==200, use Resolve ("success!"); Callback, if not, use Reject (Error ("fail"));
3. Step three: Use Promise.then to listen to these two callback functions and make the corresponding actions we expect to succeed or fail.

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.