Examples of the use of promise in JavaScript basic knowledge

Source: Internet
Author: User
Tags error handling object object

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:

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:
 
object.save ({key:value}). Then (
 function (object) {
  //the object was saved.
 },
 function (Error) {
  //saving the object failed.
 });

Not much of a 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 finish. 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:

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:

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:

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) {
      //The 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 an error without performing any callbacks until an error is encountered. For example, the above code can be abbreviated as:

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.

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'll reach this and result = = "It's all Good.".
},function (Error) {
 //JQuery would reach this with error = = "It's all Good."
);

&NBSP
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!

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.