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
- var $info = $ (
- $.ajax ({
- "/echo/json/",
- data: { json: json.stringify ({ " Somevalue "}) },
- type: "POST",
- success: function (response)
-     {  
- $info. Text (response.name);
-     }  
- });
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
- var $info = $ ("#info");
- $.ajax ({
- URL: "/echo/json/",
- Data: {
- Json:JSON.stringify ({
- "name": "somevalue"
- })
- },
- Type: "POST"
- })
- . Then (function (response) {
- $info. Text (response.name);
- });
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
- var $info = $ ("#info");
- $.ajax ({
- URL: "/echo/json/",
- Data: {
- Json:JSON.stringify ({
- "name": "somevalue"
- })
- },
- Type: "POST"
- })
- . Then (function (response) {
- $info. Text (response.name);
- })
- . Then (function () {
- $info. Append ("... More ");
- })
- . Done (function () {
- $info. Append ("... finally!");
- });
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
- var $info = $ ("#info");
- $.ajax ({
- //change URLs to see error happen
- URL: "/echo/json/",
- Data: {
- Json:JSON.stringify ({
- "name": "somevalue"
- })
- },
- Type: "POST"
- })
- . Then (function (response) {
- //Success
- $info. Text (response.name);
- },
- function () {
- //Failure
- $info. Text ("Bad things happen to good developers");
- })
- . Always (function () {
- $info. Append ("... finally");
- });
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
- var m = angular.module ("myApp", []);
- M.factory ("DataService", function ($q) {
- function _callme () {
- var d = $q. Defer ();
- SetTimeout (function () {
- D.resolve ();
- //defer.reject ();
- }, 100);
- return d.promise;
- }
- return {
- CallMe: _callme
- };
- });
- function Myctrl ($scope, DataService) {
- $scope. Name = "None";
- $scope. isBusy = true;
- Dataservice.callme ()
- . Then (function () {
- //Successful
- $scope. Name = "Success";
- },
- function () {
- //Failure
- $scope. Name = "Failure";
- })
- . Then (function () {
- //Like a Finally Clause
- $scope. IsBusy = false;
- });
- }
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"