JavaScript Asynchronous Programming Assistant: Promise Mode "Go"

Source: Internet
Author: User

Asynchronous mode is becoming more and more important in web programming, which is not very easy to implement for Web-leading language JavaScript, so many JavaScript libraries (such as jquery and Dojo, AngularJS) Adds an abstraction called promise (the term is called deferred mode). Through these libraries, developers can use the promise pattern in real programming, each promise has a unique interface called then, and when the promise fails or succeeds, it makes callbacks. It represents a result of operations that may be long-running and not necessarily complete. This mode does not block and wait for long operations to complete, but instead returns an object that represents the promised (promised) result.

In this article we will discuss how JavaScript libraries (such as jquery, AngularJS) use promise mode to handle asynchrony, in fact, by providing fault-tolerant support in the form of callbacks.

Let's take a look at how jquery operates:

[JS]View Plaincopy
    1. var  $info  = $ (
    2. $.ajax ({  
    3. "/echo/json/",   
    4.      data: { json: json.stringify ({ " Somevalue "})  },  
    5.     type: "POST",   
    6.     success: function (response)   
    7.     {  
    8.         $info. Text (response.name);   
    9.     }  
    10. });  
In this example, you can see that a callback is specified when the setting is successful, which is not a promise, but a good callback method. When the AJAX call is complete, it executes the success function. Depending on the asynchronous operation used by the library, you can use a variety of different callbacks (that is, if the task succeeds, the callback is made, and the response is done). Using promise mode simplifies this process, and asynchronous operations simply return an object call. This promise allows you to invoke a method called then, and then lets you specify the number of function (s) for the callback, let's look at how jquery builds promise: [JS]View Plaincopy
  1. var $info = $ ("#info");
  2. $.ajax ({
  3. URL: "/echo/json/",
  4. Data: {
  5. Json:JSON.stringify ({
  6. "name": "somevalue"
  7. })
  8. },
  9. Type: "POST"
  10. })
  11. . Then (function (response) {
  12. $info. Text (response.name);
  13. });

Interestingly, the Ajax object returns the Xhr object to implement promise mode, so we can call the then method, and the advantage is that you can make a chained call that implements the standalone operation as follows:

[JS]View Plaincopy
  1. var $info = $ ("#info");
  2. $.ajax ({
  3. URL: "/echo/json/",
  4. Data: {
  5. Json:JSON.stringify ({
  6. "name": "somevalue"
  7. })
  8. },
  9. Type: "POST"
  10. })
  11. . Then (function (response) {
  12. $info. Text (response.name);
  13. })
  14. . Then (function () {
  15. $info. Append ("...  More ");
  16. })
  17. . Done (function () {
  18. $info. Append ("... finally!");
  19. });

Because many libraries are beginning to adopt promise mode, asynchronous operations can become very easy. But what would promise be like if you were to think in the opposite direction? One of the most important patterns is that a function can accept two functions, one is the callback when it succeeds, and the other is the callback when it fails.

[JS]View Plaincopy
  1. var $info = $ ("#info");
  2. $.ajax ({
  3. //change URLs to see error happen
  4. URL: "/echo/json/",
  5. Data: {
  6. Json:JSON.stringify ({
  7. "name": "somevalue"
  8. })
  9. },
  10. Type: "POST"
  11. })
  12. . Then (function (response) {
  13. //Success
  14. $info. Text (response.name);
  15. },
  16. function () {
  17. //Failure
  18. $info. Text ("Bad things happen to good developers");
  19. })
  20. . Always (function () {
  21. $info. Append ("... finally");
  22. });

It is important to note that in jquery, whether successful or unsuccessful, we use a tune to specify what we want to invoke. Let's take a look at how Angularjs uses promise mode:

[JS]View Plaincopy
  1. var m = angular.module ("myApp", []);
  2. M.factory ("DataService", function ($q) {
  3. function _callme () {
  4. var d = $q. Defer ();
  5. SetTimeout (function () {
  6. D.resolve ();
  7. //defer.reject ();
  8. }, 100);
  9. return d.promise;
  10. }
  11. return {
  12. CallMe: _callme
  13. };
  14. });
  15. function Myctrl ($scope, DataService) {
  16. $scope. Name = "None";
  17. $scope. isBusy = true;
  18. Dataservice.callme ()
  19. . Then (function () {
  20. //Successful
  21. $scope. Name = "Success";
  22. },
  23. function () {
  24. //Failure
  25. $scope. Name = "Failure";
  26. })
  27. . Then (function () {
  28. //Like a Finally Clause
  29. $scope. IsBusy = false;
  30. });
  31. }

You can try these examples in jsfiddle and see what the results will be. Using promise to operate async is a very simple way, and simplifying your code is not a good way to double benefit.

For more information about promise and examples, you can visit our website.

From: JavaScript Promise

This article for CSDN compilation, without permission not reproduced, if necessary reprint please contact market#csdn.net (#换成 @)

JavaScript Asynchronous Programming Assistant: Promise Mode "Go"

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.