search
HomeWeb Front-endJS TutorialDetailed 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!

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool