For example, explain how to use Promise in JavaScript, javascriptpromise

Source: Internet
Author: User

For example, explain how to use Promise in JavaScript, javascriptpromise

Excerpt-the Parse JavaScript SDK now provides a Promises mode compatible with jquery that supports most asynchronous methods. What does this mean? You will understand it after reading the following.

"Promises" represents the next great paradigm in javascript programs, but it is not easy to understand why they are so great. At its core, a promise represents a task result, which may fail to be completed. The only interface required by Promise mode is to call the then method, which can be used to register the callback function called when promise is completed or fails, which is mentioned in CommonJS Promises/A proposal. For example, I want to save a Prase. Object, which is an asynchronous operation. In the old callback paradigm, your code may be written as follows:
 

Object. save ({key: value}, {success: function (object) {// the object was saved .}, error: function (object, error) {// saving the object failed .}}); in the new Promise paradigm, you can write the same code as follows: object. save ({key: value }). then (function (object) {// the object was saved .}, function (error) {// saving the object failed .});

No big difference? So what's the big deal? Well, the true strength of promises lies in multiple links. When promise. then (func) is called, a new promise is returned and it will not be executed until the previous one is completed. However, there is a special case. If my callback returns a new promise through then, the promise returned through then will not be executed until the callback execution is completed. For details, see Promises/A +. This is A complex rule. We can better understand it through examples.


Suppose you have written the code for segment login, search for the object, and update it. In the old callback paradigm, you can use the pyramid code to complete:
 

Parse.User.logIn("user","pass", { success:function(user) {  query.find({   success:function(results) {    results[0].save({ key: value }, {     success:function(result) {      // the object was saved.     }    });   }  }); }});

This seems ridiculous. What's even more ridiculous is that there is no error handling. However, the promise chain structure makes the Code look more comfortable:
 

Parse.User.logIn("user","pass").then(function(user) { returnquery.find();}).then(function(results) { returnresults[0].save({ key: value });}).then(function(result) { // the object was saved.});

Wow! A lot!


Error Handling

No error handling is added during the above Code, but after the code is added, you will find a mess in the old callback code:
 

Parse.User.logIn("user","pass", { success:function(user) {  query.find({   success:function(results) {    results[0].save({ key: value }, {     success:function(result) {      // the object was saved.     },     error:function(result, error) {      // An error occurred.     }    });   },   error:function(error) {    // An error occurred.   }  }); }, error:function(user, error) {  // An error occurred. }});

Because promises knows whether the processing is complete, it can pass errors without executing any callback until an error is encountered. For example, the above Code can be abbreviated:
 

Parse.User.logIn("user","pass").then(function(user) { returnquery.find();}).then(function(results) { returnresults[0].save({ key: value });}).then(function(result) { // the object was saved.},function(error) { // there was some error.});

Generally, developers think that an asynchronous promise failure is equivalent to throwing an exception. In fact, if a callback throws an error, promise returns the failure message. Passing an error to the next available error processor is equivalent to throwing an exception until it is captured and processed.


JQuery, Backbone, and Parse

There are many libraries that implement promises for developers to use. Deferred like jQuery, Microsoft's WinJS. Promise, when. js, q, and dojo. Deferred.

However, there is something interesting to know. You can read the long and fascinating jQuery pull request discussion here. jQuery's implementation does not follow the rules of Promises/A. In many cases, other implementation methods are used. During the experiment, I found that only one place is not the same. If an error processor returns some other information instead of simply returning a promise, most implementations will consider handling this error without passing the error. However, jquery does not consider this error to be handled here, but transmits it forward. Although promise from different systems should be seamlessly mixed, you should pay attention to it. A potential problem is that promises (replacing the original value) is returned in the error processor because they are treated equally.
 

doFailingAsync().then(function() { // doFailingAsync doesn't succeed.},function(error) { // Try to handle the error. return"It's all good.";}).then(function(result) { // Non-jQuery implementations will reach this with result === "It's all good.".},function(error) { // jQuery will reach this with error === "It's all good.".});

 
In the latest version of Backbone 0.9.10, the Asynchronous Method now returns a jqXHR, a type of jquery promise. One goal of the Parse JavaScript SDK is to be as compatible with Backbone as much as possible. We cannot return a jqXHR because it does not work well on Cloud Code. Therefore, we do not add a Parse. promise class, which complies with jQuery Deferred standards. The latest version of the Parse JavaScript SDK has updated all asynchronous methods to support these new objects. The old callback method is still available. However, based on the examples listed above, I believe you prefer the new method. So try promises!

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.