Javascript asynchronous programming model Promise mode details _ javascript skills

Source: Internet
Author: User
Tags types of functions
Asynchronous mode becomes more and more important in Web programming. It is a headache to handle the operations after asynchronous requests. Promise is an asynchronous programming model called the Deferred mode. It standardizes asynchronous operations through a set of APIS, Making Process Control of asynchronous operations easier. The Promise programming mode is also called thenable, which can be understood as delayed execution. Each Promise has a unique API called then. When Promise fails or succeeds, it performs a callback. It represents an operation result that may run for a long time and may not necessarily be completed. This mode does not block or wait for a long time to complete the operation, but returns an object that represents the promised result.

Many of the current JavaScript libraries (such as jQuery, Dojo, and AngularJS) have added this abstraction called Promise. With these libraries, developers can use the Promise mode in actual programming.

Next we will take jQuery as an example to discuss how the JavaScript library uses the Promise mode to process Asynchronization. In fact, it provides Fault Tolerance support through callback. If an operation succeeds or fails, or the corresponding callback is executed under any circumstances, handle all possible logical situations.

First, let's take a look at how jQuery operates normally:

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 when the setting is successful, a callback is specified, which is a good callback method. This is not a Promise, this approach (http://api.jquery.com/jQuery.ajax/#jqXHR) is also not recommended in jQuery official documentation ). After Ajax is called, it executes the success function. Depending on the asynchronous operations used by the database, you can use various callbacks (that is, whether the task is successful or not, the callback will be performed and the response will be made ). Using the Promise mode simplifies this process. asynchronous operations only need to return an object call. This Promise allows you to call a method called then, and then let you specify the number of functions (s) for callback.

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

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 );
});

JQuery ajax objects implement the Promise mode by returning xhr objects, so we can call the then method. The advantage of this method is that you can chain the call to implement independent operations, as shown below:

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! ");
});

Because many databases start to adopt the Promise mode, asynchronous operations become very easy. But what will Promise look like from the opposite perspective? One of the most important modes is that a function can accept two types of functions. One is the callback upon success, and the other is the callback upon failure.

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, no matter whether it is successful or failed, we will use a call to specify what we want to call.
In fact, this can also be written here, which is also recommended in the jQuery official document:

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 ");
});

Next let's take a look at how AngularJS uses the Promise mode:

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 );
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 results will be produced. Using Promise to operate Asynchronization is a very simple method, and it can also simplify your code. It is indeed a good way to put everything together.

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.