JavaScript Promise Technology __java

Source: Internet
Author: User

You may already know that promises is now part of the JavaScript standard. The Chrome beta version has implemented the basic promise API. Today, the concept of promise is nothing new in web development. Most of us have used promises in some popular JS libraries such as Q, when, and Rsvp.js. Even jquery has a similar thing to promises, called deferred. But JavaScript native support for promises is really a very exciting thing. This article will first tell you the basics of promises and show you how to make good use of promises in your JS development.

Note: At present promises is only an experimental feature, currently only chrome Beta and the latest version of Firefox support. A summary of promises

A Promise object represents a value that is not available at this time, but can be resolved at some point in the future. It allows you to write asynchronous code in a synchronized fashion. For example, if you want to use the Promise API to invoke a remote server asynchronously, you need to create a promise object that represents the data that will be returned by the Web service in the future. The only problem is that the current data is not available yet. When the request completes and returns from the server, the data becomes available. During this time, the Promise object will act as a proxy role for real data. Next, you can bind a callback function to the Promise object, and the callback function will be invoked once the real data becomes available. API for Promise

Before we start writing code, we'll create a promise object with the following code:

if (window. Promise) {//check to see if the browser supports Promise
    var Promise = new Promise (function (resolve,reject) {
        //write asynchronous code here
    });
   

We instantiate a Promise object and pass a callback function to it. This callback function receives two parameters, resolve () and reject (), which are all functions. All of your code will be in the callback function, and if all goes well, promise will call resolve () and become a fulfilled state. In the event of an error, reject () will be invoked along with an Error object, which indicates that the promise becomes a rejected state.

Now let's write a simple example to show the usage of promise. The following code makes an asynchronous request to a Web service that will randomly return a JSON-formatted joke. Let's take a look at how promise is used here:

if (window.   

    Promise) {console.log (' Promise found ');

        var promise = new Promise (function (resolve,reject) {var request = new XMLHttpRequest ();

        Request.open (' Get ', ' http://api.icndb.com/jokes/random '); Request.onload = Fucntion () {if (Request.status =) {resolve (Request.response);//We got a number here
        As a result, parse Promise}else{reject (Error (request.statustext));//Status code is not 200, so call reject}

        };
        Request.onerror = function () {Reject (Error (' Error fetching data ');//error occurrence, reject promise}; Request.send ();

    Send request});  

    Console.log (' asynchronous request made. '); Promise.then (function (data) {Console.log (' Got data!
        Promise fulfilled. ');
    Document.getelementbytagname (' body ') [0].textcontent = Json.parse (data). Value.joke;
        },function (Error) {Console.log (' Promise rejected ');
    Console.log (Error.message);
}); else {Console.log(' Promise not available ');   
 }

In the above code, the callback function in the Promise () constructor contains a section of asynchronous code used to fetch data from the remote server. Here, we just created an AJAX request from Http://api.icndb.com/jokes/random to randomly return a joke. When the JSON response returned by the remote server is received, it is passed to resolve (). In the event of an error, reject () is invoked along with an Error object.

When we instantiate a promise object, we get a proxy that says that the data will be available at some point in the future. In the example above, we expect some data to be returned from the remote server at some point in the future. So, how do we have nightmares about when the data is available? That's why you use Promise.then (). function then () receives two parameters: a successful callback and a failed callback. These callback functions are invoked when promise is in a settled state (fulfilled or rejected). If the promise is in a fulfilled state, the successful callback function will be triggered along with the data that you pass to resolve (). If promise is in the rejected state, the failed callback function will be invoked. Whatever arguments you pass to the Reject () function are passed to the callback function.

There are three states of promise: Pending (no fulfilled or rejected) fulfilled rejected

The Promise.status property, which is a private property that the code cannot obtain, is used to represent the above bands. Once a promise becomes rejected or fulfilled, the State is permanently associated with it. This means that a promise can only succeed or fail once. If promise is already in the fulfilled state and then you bind the then () method on top of it with two callback functions, then the successful callback will be called correctly. Therefore, in the promise world, we are not interested in knowing when promise will be finished. We only care about the final output of promise. Chain type promises

Sometimes we want to assemble the promises chain. For example, you might have multiple callback operations. When an operation returns a data to you, you will start another operation based on this data, and so on. The following code will show you how to do chained-promises operations:

function getpromise (URL) {
    ///Return a Promise
    //Send an asynchronous request to the URL as part of the promise/
    /After the result is obtained, along with the data parsing promise
}  

var promise = getpromise (' Some URL here ');  

Promise.then (function (Result) {
    //We'll get the results here
    return getpromise (outcome);//Returns a promise here again 
). Then ( function (Result) {
    //process final results
});   

The trick in this section is that when you return a simple value in then (), the next then () will be invoked along with the return value. But if you return a promise in then (), the next then () will not be invoked until the promise is complete. Handling Errors

The then () function is now known to receive two callback functions as arguments. The second callback function was dropped when promise changed to rejected. However, we also have a catch () function to handle the rejected state of the promise. Let's take a look at the following code:

Promise.then (fucntion (Result) {
    console.log (' Got data! ', relust);
}). catch (function (error) {
    console.log (' Error occurred! ', error);
});

It is equivalent to:

Promise.then (function (result) {
    consoe.log (' Got data ', result);
},function (Error) {
Console.log (' Error occurred! ', error);
 

Note that if promise is in the rejected state and then () does not have a failed callback function, then the control will move to the next catch (), the then () that has the failed callback function. In addition to explicitly handling the promise rejected state, catch () is invoked when the promise () constructor function callback throws an error. Therefore, you can still use catch () to achieve the role of the log. Note that we use Try...catch to handle errors, but we do not need to use this method in promise because of catch (), whether synchronous or asynchronous. Summary

The

is summarized in this article for a brief introduction to the new Promise API in JavaScript. Obviously it makes it easier for us to write code. We can move forward without knowing the return value of the asynchronous code in the future. The Promise API also contains a lot of things that we'll talk about later.

Related Article

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.