How to Use Promises to write more elegant JavaScript code, promisesjavascript

Source: Internet
Author: User

How to Use Promises to write more elegant JavaScript code, promisesjavascript

You may have accidentally heard of Promises. Many people are discussing it and using it, but you don't know why they are so special. Can't you use callback? What's special? In this article, let's take a look at what Promises are and how to use them to write more elegant JavaScript code.

Promises easy to read

For example, we want to capture some data from the HipsterJesus API and add the data to our page. The response data of these Apis is as follows:

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

To Use callback, we usually need to write something in the following format:

$.getJSON('http://hipsterjesus.com/api/', function(data) {  $('body').append(data.text); }); 

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

Another writing method is to use the promise object returned by the getJSON method. You can bind a callback directly to the returned object.

var promise = $.getJSON('http://hipsterjesus.com/api/');promise.done(function(data) {  $('body').append(data.text); }); 

In the preceding callback example, when the response is successful, it adds the results of the API request to the document. But what happens when the response fails? We can bind a failure processor to our promise.

var promise = $.getJSON('http://hipsterjesus.com/api/');promise.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 be seen at a glance.

$.getJSON('http://hipsterjesus.com/api/').done(function(data) {  $('body').append(data.text);}).fail(function() {  $('body').append('<p>Oh no, something went wrong!</p>'); }); 

JQuery also contains a constantly occurring event processor, which is called no matter whether the request succeeds or fails.

$.getJSON('http://hipsterjesus.com/api/').done(function(data) {  $('body').append(data.text);}).fail(function() {  $('body').append('<p>Oh no, something went wrong!</p>');}).always(function() {  $('body').append('<p>I promise this will always be added!.</p>'); }); 

By using promise, the callback sequence is as expected. We can ensure that the normal callback is called first, then the failure callback, and finally the ongoing callback.

Better API

For example, we want to create an encapsulation object for the HipsterJesus API. We will add a method -- html, which returns HTML data from the API. Unlike setting a callback processor to parse requests, 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 that we can bypass the promise object without worrying about when or how to parse its value. For any code that requires the return value of promise, you only need to register a successful response callback.

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

hipsterJesus.html().done(function(html) {  $("body").append(html); }); 

Until recently, AngularJS has a killer feature, and templates can be directly bound to promise. In Angular controllers, such:

$scope.hipsterIpsum = $http.get('http://hipsterjesus.com/api/'); 

In this way, writing {hipsterIpsum. text} in the template is simple. After promise resolution, Angular does not need to update the view automatically. Unfortunately, the Angular team has abandoned this feature. Now, it can be enabled by calling $ parseProvider. unwrapPromises (true. I hope other Angular frameworks have always included this feature (I will keep an eye on it ).

Chain call

The most brilliant part of Promise is that you can concatenate them. For example, we want to add a method to an API that returns an array.

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 the preceding HTML method in the paragraphs method. Because the return value of the promise callback function is passed to the next Callback in the chain, we can freely create small and functional methods to change data when using them.

We can concatenate 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

The most notable feature of promise is the ability to call multiple APIs. When using callback, what will happen if you need to create two API calls at the same time? You may write as follows:

var firstData = null;var secondData = null;var responseCallback = function() {   if (!firstData || !secondData)   return;   // do something}$.get("http://example.com/first", function(data) {  firstData = data;  responseCallback();});$.get("http://example.com/second", function(data) {  secondData = data;  responseCallback(); }); 

If promise is used, 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 called when both requests are completed.

Conclusion

This is Promise. I hope you will immediately think of some terrible things that can be implemented using Promise. What are your favorite ways to use them? Let me know in the comment!

* Note: For the sake of simplicity, this article uses jQuery's deferred execution. There is A slight difference between the Deferred object of jQuery and the Promises/A + specification, which is more standard.

In this article, how to use Promises to write more elegant JavaScript code is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.

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.