Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of Promise in JavaScript with examples_Basic knowledge

Detailed explanation of the use of Promise in JavaScript with examples_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:53:011120browse

Excerpt – Parse JavaScript SDK now provides jquery-compatible Promises mode that supports most asynchronous methods, so what does this mean, you will understand after reading the following.

"Promises" represent the next great paradigm in JavaScript programming, but understanding why they are so great is not simple. Its core is that a promise represents a task result, which may or may not be completed. The only interface required by the Promise mode is to call the then method, which can be used to register a callback function that is called when the promise is completed or failed. This is generally discussed in CommonJS Promises/A proposal. For example, I want to save a Prase.Object object. This is an asynchronous operation. In the old callback paradigm, your code might be written like this:

object.save({ key: value }, {
 success:function(object) {
  // the object was saved.
 },
 error:function(object, error) {
  // saving the object failed.
 }
});
在新的Promise范式中,同样的代码你可以这样写:
 
object.save({ key: value }).then(
 function(object) {
  // the object was saved.
 },
 function(error) {
  // saving the object failed.
 });

Not much difference? So what’s the big deal? Well, the real power of promises is the chaining of multiples. When promise.then(func) is called, a new promise is returned, which is not executed until the previous one is completed. But there is a special case here, if my callback returns a new promise through then, then the promise returned through then will not be executed until the callback execution is completed. Please refer to Promises/A for details. This is a complex rule. We can understand it more clearly through examples.


Suppose you write a login code that looks for an object and then updates it. In the old callback paradigm, you could use pyramid code completion:

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 already looks ridiculous, but what’s even more ridiculous is that there isn’t even any error handling. But 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! So many!


Error handling

The above code did not add error handling when it was simple, but after adding it you will find that it is 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.
 }
});

Since promises know whether processing is complete, it can pass errors without executing any callback 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 was saved.
},function(error) {
 // there was some error.
});

Usually, developers think that an asynchronous promise failure is equivalent to throwing an exception. In fact, if a callback throws an error, the promise will return a failure message. Passing the error to the next available error handler is equivalent to throwing an exception until it is caught.


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 something interesting to know. You can read the long and fascinating jQuery pull request discussion here. The implementation of jQuery does not completely follow the rules of Promises/A. Other implementation methods are used in many places. When experimenting, I found that there was only one difference. If an error handler returns some other information than simply returning a promise, most implementations will consider handling the error without propagating the error. However, jquery doesn't think to handle this error here and instead passes it forward. Although promises from different systems should mix seamlessly, you should still be careful. One potential problem is that promises are returned (replacing the original values) in the error handler, since 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, async methods now return a jqXHR, which is a type of jQuery promise. One of the goals of the Parse JavaScript SDK is to be as compatible with Backbone as possible. We can't return a jqXHR because it doesn't work well with Cloud Code. Therefore, we don't all add a Parse.Promise class, It follows the jQuery Deferred standard. Parse JavaScript SDKThe latest version has updated all asynchronous methods to support these new objects, and the old callback methods are still available. But based on the examples listed above, I believe you prefer the new way. So try promises!

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