Home >Web Front-end >JS Tutorial >Javascript asynchronous programming model Promise mode detailed introduction_javascript skills

Javascript asynchronous programming model Promise mode detailed introduction_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:49:201146browse

Promise programming mode is also called thenable, which can be understood as delayed execution. Each Promise has a unique interface called then, which calls back when the Promise fails or succeeds. It represents the result of an operation that may be long-running 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 promised result.

Many current JavaScript libraries (such as jQuery and Dojo, AngularJS) add this abstraction called Promise. Through these libraries, developers can use the Promise pattern in real-world programming.

Below we will use jQuery as an example to discuss how the JavaScript library uses the Promise mode to handle asynchronous processing. In fact, it provides fault-tolerance support through callbacks. Execute the corresponding callback when an operation succeeds or fails, or under any circumstances, and try to handle all situations that may occur in a certain piece of logic.

First let’s take a look at how jQuery generally operates:

Copy code The code is 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 a callback will be specified when the setting is successful, which is a good callback method. This is not a Promise, and jQuery official documentation no longer recommends this method (http:// api.jquery.com/jQuery.ajax/#jqXHR). When the Ajax call completes, it executes the success function. Depending on the asynchronous operations used by the library, you can use various callbacks (that is, whether the task is successful or not, a callback will be made to respond). Using the Promise pattern will simplify this process, and the asynchronous operation only needs to return an object call. This Promise allows you to call a method called then, which then lets you specify the number of callback function(s).

Let's take a look at how jQuery creates a Promise:

Copy the code The code is 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 mode by returning the xhr object, so we can call the then method. The advantage of this is that you can chain calls to achieve independent operations, as shown below:

Copy code The code is 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!");
});

Since many libraries are beginning to adopt the Promise pattern, asynchronous operations will become very easy. But if you think about it from the opposite perspective, what would Promise look like? One very important pattern is that a function can accept two functions, a callback on success and a callback on failure.

Copy code The code is as follows:

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

$.ajax({
// Change URL 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 should be noted that in jQuery, regardless of success or failure, we will use a call to specify what we want to call.
In fact, you can also write it like this, which is also the method recommended in the official jQuery documentation:

Copy code The code is as follows:

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

$.ajax({
// Change URL to see 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 take a look at how AngularJS uses the Promise pattern:

Copy code The code is 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); 🎜 > };
});

function myCtrl($scope, dataService) {
$scope.name = "None";
$scope.isBusy = true;
dataService.callMe()

.then(function ( ) {

                                                                                                                                                                     
                                                                                                                                               

You can try these examples in JSFiddle and see what happens. Using Promise to operate asynchronously is a very simple way, and it can also simplify your code. It is indeed a good way to kill two birds with one stone.
For more introduction and examples of Promise, you can go to the official website (http://www.promisejs.org/).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn