This article mainly introduces the use of promise in JavaScript, especially the promise use of jquery is the hot in the current development circle, need friends can refer to the
Excerpt –parse The JavaScript SDK now offers a promises model that supports most asynchronous methods, so what does that mean, and you'll understand when you read the following.
"Promises" represents the next great paradigm in JavaScript programs, but it is not easy to understand why they are so great. Its core is that a promise represents a task that may or may not have been completed. The only interface required for Promise mode is to call the then method, which can be used to register a callback function that is invoked when promise completes or fails, in Commonjs promises/a proposal. Roughly speaking. For example, I want to save a Prase.object object, which is an asynchronous operation that your code might write in the old callback paradigm:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 |
Object.save ({Key:value}, {success:function (object) {//The object was saved.}, Error:function (object, error) {//SA Ving Tsun object failed. } }); In the new promise paradigm, you can write the same code: Object.save ({key:value}). Then (function (object) {//The object was saved.}, function (err OR) {//Saving the object failed.}); |
No big difference? So what's the big deal? Well, the real strength of promises is that multiple links, when called Promise.then (func) return a new promise, and it does not execute until the last completes. But there is a special situation where if my callback returns a new promise through then, the promise returned through then will not be executed until the callback execution completes. Please refer to promises/a+ for details, this is a complex rule, and we can understand it more clearly by example.
Suppose you write a login code, look up the object and update it. In the old callback paradigm, you can use the Pyramid code to do this:
?
1 2 3 4 5 6 7 8 9 10 11 12-13 |
Parse.User.logIn ("User", "pass", {success:function (user) {Query.find ({success:function (results) {Results[0].save) ({ Key:value}, {success:function (Result) {//The object is saved.}}); } }); } }); |
This seems ridiculous, and even more ridiculous is that there is no error handling. But the promise-chained structure makes the code look more comfortable:
?
1 2 3 4 5 6 7 |
Parse.User.logIn ("User", "Pass"). Then (function (user) {Returnquery.find ();}). Then (function (results) {Returnresults[0].save ({key:value});}). Then (function (Result) {//The object is saved.}); |
Wow, much better!
Error handling
The above code does not add error handling during the simple period, but after you add it you will find that the old callback code is a mess:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 |
Parse.User.logIn ("User", "pass", {success:function (user) {Query.find ({success:function (results) {Results[0].save) ({ Key:value}, {success:function (Result) {//The object is saved.}, Error:function (result, error) {//An error Occurre D.}); }, Error:function (Error) {//An error occurred.}}); }, error:function (user, error) {//An error occurred.}}); |
Because promises knows whether the processing is complete, it can pass an error without performing any callbacks until an error is encountered. For example, the above code can be abbreviated as:
?
1 2 3 4 5 6 7 8 9 |
Parse.User.logIn ("User", "Pass"). Then (function (user) {Returnquery.find ();}). Then (function (results) {Returnresults[0].save ({key:value});}). Then (function (Result) {//The object is saved.},function (Error) {//There was some error.}); |
Typically, a developer thinks that an asynchronous promise failure equates to throwing an exception. In fact, if a callback throws an error, promise returns the failure message. Passing the error to the next available error handler is equivalent to throwing an exception until the capture is processed.
JQuery, backbone, and Parse
There are many libraries that implement promises for developers to use. Like jquery's Deferred, Microsoft's winjs.promise, When.js, Q, and dojo. Deferred.
However, there is an interesting place to learn. You can read here the long and fascinating jquery pull request discussion, the implementation of jquery is not exactly according to the promises/a rules, many places use other implementation way, experiment, I find that there is only one place that is different. If an error handler returns some other information instead of simply returning a promise, most implementations will consider handling the error without passing the error. However, jquery does not think to handle this error here, but to pass it forward. Although promise from different systems should be seamlessly mixed, you should pay attention. A potential problem is to return promises (replace the original values) in the wrong processor because they will be treated equally.
?
1 2 3 4 5 6 7 8 9 10 |
Dofailingasync (). Then (function () {//Dofailingasync doesn ' t succeed.},function (Error) {//Try to handle the error. Retu RN "It" all Good. ";}). Then (function (Result) {//Non-jquery implementations'll reach this and result = = "It's all Good.".},function (Error) {//JQuery would reach this with error = = "It's all good."); |
In the latest version of Backbone 0.9.10, the asynchronous method now returns a JQXHR, which is a type of jquery promise. One goal of the Parse JavaScript SDK is to be as compatible as possible with backbone, and we can't return a jqxhr because it doesn't work well on Cloud code, so we don't all add a Parse.promise class, which complies with the jquery deferred standard. The latest version of the Parse JavaScript SDK has updated all asynchronous methods to support these new objects, and the old callback method is still available. But based on the examples listed above, I believe you prefer the new approach. So try promises it!