How to use promises to write more elegant JavaScript code _javascript tips

Source: Internet
Author: User

You may have overheard promises, a lot of people are talking about it, using it, but you don't know why they're so special. Can't you use a callback? What's so special about it? In this article, let's look at what promises is and how to use them to write more elegant JavaScript code.

Promises easy to read

For example, we want to grab some data from the Hipsterjesus API and add that data to our page. The response data for these APIs are in the following form:

{ 
 "text": "<p>lorem ipsum...</p>", 
 "params": { 
 "paras": 4, 
 "type": "Hipster-latin" 
}} 

To use callbacks, we usually write something like the following:

$.getjson (' http://hipsterjesus.com/api/', function (data) { 
 $ (' body '). Append (Data.text); 
 

If you have jQuery experience, you will recognize that we created a GET request and want the response content to be JSON. We also passed a callback function to accept the JSON of the response to add the data to the document.

Another writing method is the Promise object returned using the Getjson method. You can bind a callback directly to the returned object.

var promise = $.getjson (' http://hipsterjesus.com/api/');p romise.done (function (data) { 
 $ (' body '). Append ( Data.text); 
}; 

In the previous callback example, when the response succeeds, it adds the results of the API request to the document. But what happens when the response fails? We can bind a failed processor on our promise.

var promise = $.getjson (' http://hipsterjesus.com/api/');p romise.done (function (data) { 
 $ (' body '). Append ( Data.text);}; Promise.fail (function () { 
 $ (' body '). Append (' <p>oh No, something went wrong!</p> '); 
}); 

Most people delete the promise variable, which is more concise and can see the function of the code at a glance.

$.getjson (' http://hipsterjesus.com/api/'). Done (the function (data) { 
 $ (' body '). Append (Data.text);}). Fail (function () { 
 $ (' body '). Append (' <p>oh No, something went wrong!</p> '); 
}); 

JQuery also contains a consistently occurring event handler that is invoked regardless of the successful failure of the request.

$.getjson (' http://hipsterjesus.com/api/'). Done (the function (data) { 
 $ (' body '). Append (Data.text);}). Fail (function () { 
 $ (' body '). Append (' <p>oh No, something went ');}). Always (function () { 
 $ (' body '). Append (' <p>i promise this'll always be added!. </p> '); 
 

By using promise, the order of callbacks is as expected. We can make sure that the normal callback is invoked first, then the failure callback, and finally the callback that is always there.

A better API

For example, we want to create a package object for the Hipsterjesus API. We will add a method--html that will return the HTML data from the API. Unlike the previous setting of a callback handler to parse the request, we can let the method return a Promise object.

var hipsterjesus = { 
 html:function () {return 
  $.getjson (' http://hipsterjesus.com/api/'). Then (function (data {return 
   data.text; 
  };}; 
 

This is cool, so we can bypass the promise object without having to worry about when or how to parse its value. Any code that requires a promise return value can only register a successful response callback.

The then method allows us to modify the results of the promise and pass it on to the next processor in the chain. This means that we can now use the new API in this way:

Hipsterjesus.html () Done (function (HTML) { 
 $ (' body '). Append (HTML); 
 

Until recently, Angularjs had a killer feature, and templates could be tied directly to promise. In the angular controller, like this:

$scope. hipsteripsum = $http. Get (' http://hipsterjesus.com/api/'); 

In this way, writing {{Hipsteripsum.text}}} in the template is simple. When promise resolves, angular does not need to update the view automatically. Unfortunately, the angular team has abandoned this feature. It can now be enabled by calling $parseProvider. Unwrappromises (True). I hope angular has been included in other frameworks (I will keep my eye on it).

Chained call

The best part of Promise is that you can concatenate them together. Let's say we want to add a method to an API that returns an array of arrays.

var hipsterjesus = { 
 
 html:function () {return 
  $.getjson (' http://hipsterjesus.com/api/'). Then (function (data) {return 
   data.text; 
  }]; 
 
 paragraphs:function () {return 
  this.html (). Then (function (HTML) { Return 
   html.replace (/<[^>]+>/g, ""). Split (""); 
  }); 
 }; 

We use this HTML method in the above way, we used it in the paragraphs method. Because the return value of the promise callback function is passed to the next callback in the chain, we are free to create small, functional methods to change the data when we pass them.

We can cascade promise as needed. Let's add one.

var hipsterjesus = { 
 
 html:function () {return 
  $.getjson (' http://hipsterjesus.com/api/'). Then (function (data) {return 
   data.text; 
  }]; 
 
 paragraphs:function () {return 
  this.html (). Then (function (HTML) { Return 
   html.replace (/<[^>]+>/g, ""). Split (""); 
  }); 
 }, 
 
 sentences:function () { 
  Return This.paragraphs (). Then (function (paragraphs) {return 
   [].concat.apply ([], Paragraphs.map (function ( Paragraph) {return 
    paragraph.split (/./); 
   }); 
  }); 
 };

Multiple calls

Perhaps the most notable feature of promise is the ability to invoke multiple APIs. When using callbacks, what happens if you need to create two API calls at the same time? You might write this:

var firstdata = Null;var Seconddata = Null;var responsecallback = function () { 
 
 if (!firstdata | |!seconddata) 
  RETU RN; 
 
 Do Something}$.get ("Http://example.com/first", function (data) { 
 firstdata = data; 
 Responsecallback ();}); $.get ("Http://example.com/second", function (data) { 
 seconddata = data; 
 Responsecallback (); 
}); 

Using promise, this is much simpler:

var firstpromise = $.get ("Http://example.com/first"); 
var secondpromise = $.get ("Http://example.com/second"); 
$.when (Firstpromise, secondpromise). Done (function (Firstdata, seconddata) { 
 //do something 
}); 

Here we use the When method to bind it to a processor that is invoked when two requests are complete.

Conclusion

This is Promise. I hope you immediately think of some terrible things that can be accomplished with Promise. What is your favorite way to use them? Tell me in the comments!

* Note: For simplicity's sake, this article uses the deferred execution of jquery. There is a slight difference between the deferred object of JQuery and the specification of the promises/a+, which is more standard.

This article how to use promises to write more elegant JavaScript code is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.