Home Web Front-end JS Tutorial JavaScript asynchronous programming code writing specifications Promise study notes_javascript skills

JavaScript asynchronous programming code writing specifications Promise study notes_javascript skills

May 16, 2016 pm 04:14 PM
javascript promise Asynchronous programming

My work has become a little easier recently, and I remembered a word promise that I always saw before, so I patiently studied it for a while.

1: What is Promise? Why is there this thing?

First of all, Promise was created to solve the problem of code writing in javascript asynchronous programming.
With the development of JavaScript, there are more and more asynchronous scenarios. The front-end has AJAX, setTimeout, etc., and the back-end Node is more asynchronous. According to the traditional approach, various callbacks are embedded in callbacks. Code can be confusing.
At this time, the CommonJS community proposed a specification called Promise/A, which defines how to write asynchronous code, including using when/then/resolve, etc. to organize asynchronous code.
Because this specification is very elegant, many people have implemented it, including Promise() natively supported by browsers, deferred in jQuery, when.js, etc.
Because these libraries all comply with this specification, it is enough to learn one. I mainly learned jQuery's deferred, so this article mainly talks about this implementation.

Two: jQuery’s deferred

First of all, regarding deferred objects, teacher Ruan Yifeng has written a very detailed article, the address is here. It is recommended that you read his article first and then continue reading.
As mentioned above, promises are used to solve asynchronous problems (such as ajax), so let's compare their differences.
The classic jQuery AJAX writing method is

Copy code The code is as follows:

$.ajax({
Type: "get",
url: "",
Success: function () {},
error; function () {}
});

The success and error parameters are the callback functions when success/failure occurs.

And now jQuery’s AJAX writing method has become

Copy code The code is as follows:

$.ajax({
Type; "get",
URL: ""
}).done(function () {}).fail(function () {});

After success, the function in done will be called, and upon failure, the function in fail will be called.

When you see this, you may have questions. On which object are the done/fail methods located? What object does $.ajax() return and why are there these two methods?
The answer lies in the Deferred object introduced below.

jQuery provides a new type Deferred. Generated through $.Deferred(). For example

Copy code The code is as follows:

var def = $.Deferred();

This def inherits many methods, including done/fail/resolve/reject, etc.
So here we also know that the above $.ajax() actually returns this object.

Deferred objects have many methods. Here are some commonly used ones. For more information, please refer to API

The first thing is to naturally generate a def object. There are many methods here, such as:

Copy code The code is as follows:

var def = $.Deferred(); // Generate it yourself
$.ajax({}); // The ajax method also returns a def object
$.when(); // when method will also return a def object

Here, $.when() can be discussed separately. This method usually receives one or more deferred objects, and then determines the state of the object returned by $.when() based on the status of these deferred objects. One usage scenario is multiple ajax requests. If one of them fails, they will all be considered failures. Then you can pass in multiple ajax methods in $.when(), such as $.when($.ajax(), $. ajax()). Then $.when will return a def object (judged based on the results of these two requests).

Then after getting the def object, there are a series of methods to change the state of this object

Copy code The code is as follows:

def.resolve(); // Set the def object to completed, and then the function bound in def.done() will be executed immediately.
def.reject(); // Set the def object to have failed, and then the function bound in def.fail() will be executed immediately.
def.notify(); // When def object is executed, the corresponding callback is def.progress().

The next step is to set the callback method. The order corresponds to the above, that is, what callback will be called in what state

Copy code The code is as follows:

def.done(); // Corresponds to def.resolve();
def.fail(); // Corresponds to def.reject();
def.progress(); // Corresponds to def.notify();
// Special
def.always(); // Will be called on success or failure
def.then(); // Accept multiple functions, in order they are success (done), failure (fail) and progress (progress)

In fact, at this point, the usage of deferred objects is almost the same. However, jQuery also provides several APIs

Copy code The code is as follows:

// Check the current status class
def.isRejected();
def.isResolved();
def.state();

As the names of these APIs suggest, I won’t go into details. For details, you can check the jQuery API documentation given above.

There is another method, that is, sometimes we want to give an external def object, and then this object can set callbacks for various states, but cannot change its state, then we can use

Copy code The code is as follows:

def.promise();

Returns a promise object, which is a subset of the deferred object. You can use done/fail and other methods. There are no resolve/reject and other methods. It is mainly to protect the state of the def object from being modified by the outside.

At this point, I have finished talking about promises. You can now use it in your own projects. In addition, I wish you all a happy new year in advance and wish you all a prosperous Year of the Sheep^ ^.

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement asynchronous programming with C++ functions? How to implement asynchronous programming with C++ functions? Apr 27, 2024 pm 09:09 PM

Summary: Asynchronous programming in C++ allows multitasking without waiting for time-consuming operations. Use function pointers to create pointers to functions. The callback function is called when the asynchronous operation completes. Libraries such as boost::asio provide asynchronous programming support. The practical case demonstrates how to use function pointers and boost::asio to implement asynchronous network requests.

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

Common problems and solutions in asynchronous programming in Java framework Common problems and solutions in asynchronous programming in Java framework Jun 04, 2024 pm 05:09 PM

3 common problems and solutions in asynchronous programming in Java frameworks: Callback Hell: Use Promise or CompletableFuture to manage callbacks in a more intuitive style. Resource contention: Use synchronization primitives (such as locks) to protect shared resources, and consider using thread-safe collections (such as ConcurrentHashMap). Unhandled exceptions: Explicitly handle exceptions in tasks and use an exception handling framework (such as CompletableFuture.exceptionally()) to handle exceptions.

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

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

How does the golang framework handle concurrency and asynchronous programming? How does the golang framework handle concurrency and asynchronous programming? Jun 02, 2024 pm 07:49 PM

The Go framework uses Go's concurrency and asynchronous features to provide a mechanism for efficiently handling concurrent and asynchronous tasks: 1. Concurrency is achieved through Goroutine, allowing multiple tasks to be executed at the same time; 2. Asynchronous programming is implemented through channels, which can be executed without blocking the main thread. Task; 3. Suitable for practical scenarios, such as concurrent processing of HTTP requests, asynchronous acquisition of database data, etc.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Feb 26, 2024 am 10:00 AM

1. Why use asynchronous programming? Traditional programming uses blocking I/O, which means that the program waits for an operation to complete before continuing. This may work well for a single task, but may cause the program to slow down when processing a large number of tasks. Asynchronous programming breaks the limitations of traditional blocking I/O and uses non-blocking I/O, which means that the program can distribute tasks to different threads or event loops for execution without waiting for the task to complete. This allows the program to handle multiple tasks simultaneously, improving the program's performance and efficiency. 2. The basis of Python asynchronous programming The basis of Python asynchronous programming is coroutines and event loops. Coroutines are functions that allow a function to switch between suspending and resuming. The event loop is responsible for scheduling

See all articles