


Detailed explanation of the use of Promise in JavaScript with examples_Basic knowledge
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a
