JavaScript Asynchronous Programming model promise model detailed introduction _javascript skills

Source: Internet
Author: User

The Promise programming model is also known as thenable, which can be understood as deferred execution. Each Promise has a unique interface called then, which is invoked when Promise fails or succeeds. It represents a result of an operation that may run for a long time and does not necessarily have to be completed. Instead of blocking and waiting for a long operation to complete, this pattern returns an object that represents the result of a commitment (promised).

Many of the current JavaScript libraries (such as JQuery and Dojo, Angularjs) Add this abstraction called Promise. These libraries allow developers to use the Promise pattern in real-world programming.

Here we'll take jQuery as an example of how the JavaScript library uses the Promise mode to handle asynchrony, and in fact provides fault-tolerant support in the form of callbacks. Perform a corresponding callback in the event of a successful or unsuccessful operation or in any case, and try to handle the possible occurrence of a piece of logic.

Let's start with a look at how JQuery typically operates:

Copy Code code as follows:

var $info = $ ("#info");
$.ajax ({
URL: "/echo/json/",
Data: {json:JSON.stringify ({"Name": "Somevalue"})},
Type: "POST",
Success:function (response)
{
$info. Text (response.name);
}
});

In this example, you can see that specifying a callback when the setting is successful is a good callback, not promise,jquery official documents are no longer recommended in this way (http://api.jquery.com/jQuery.ajax/#jqXHR). When the Ajax call completes, it executes the success function. Depending on the asynchronous operation used by the library, you can use a variety of callbacks (that is, the success of the task, will be a callback, to respond). Using the Promise mode simplifies this process, and the asynchronous operation simply returns an object invocation. This Promise allows you to call a method called then, and then lets you specify the number of function (s) of the callback.

Let's take a look at how JQuery builds Promise:

Copy Code code as follows:

var $info = $ ("#info");
$.ajax ({
URL: "/echo/json/",
Data: {
Json:JSON.stringify ({
' Name ': ' Somevalue '
})
},
Type: "POST"
})
. Then (function (response) {
$info. Text (response.name);
});

The JQuery Ajax object implements the Promise pattern by returning the XHR object, so we can invoke the then method, and the advantage is that you can chain-call to implement the standalone operation, as follows:

Copy Code code as follows:

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 starting to take the Promise mode, asynchronous operations can become very easy. But what would Promise be like if you were thinking in the opposite direction? One of the most important patterns is that a function can accept two functions, one is a successful callback, the other is a callback when it fails.

Copy Code code as follows:

var $info = $ ("#info");

$.ajax ({
Change URLs to the 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 should be noted that in JQuery, both success and failure, we use a call to specify what we want to invoke.
In fact, this is also the way to write, this is the JQuery official document recommended methods:

Copy Code code as follows:

var $info = $ ("#info");

$.ajax ({
Change URLs to the error happen
URL: "/echo/json/",
Data: {
Json:JSON.stringify ({
' Name ': ' Somevalue '
})
},
Type: "POST"
})
. Done (function (response) {
Success
$info. Text (response.name);
}). Fail (function () {
Failure
$info. Text ("Bad things happen to good developers");
})
. Always (function () {
$info. Append ("... finally");
});

Let's look at how Angularjs uses the Promise mode:

Copy Code code as follows:

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 the jsfiddle, and see what effect it will have. Using Promise to manipulate asynchrony is a very simple way to simplify your code, and it's a good way to kill both birds.
For more information about promise and examples, you can go to the official website (http://www.promisejs.org/) to view.

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.