search
HomeWeb Front-endJS TutorialIn-depth understanding of js promise chain_javascript techniques

The new standard adds native Promise.

Here we only discuss the use of chains, and think about the details.

1. Review of then() and catch()

The callback function can be placed in the parameters of then() and catch() to receive the final result of a Promise.

then() can receive a parameter, then this callback will only be called when Promise resolve().

then() can also receive a second parameter, then the second callback is used to handle the Promise reject() situation.

catch() specifically handles Promise reject() situations.

In other words, then() can be used both ways, and catch() can only handle reject() situations. However, it is recommended to use then() to handle resolve() and catch() to handle reject().

Second, however, what I want to talk about is not the above. The above is just to review the basic usage. Here we start to talk about the return values ​​​​of then() and catch() and the details of chain usage.

Then the official documentation says that both then() and catch() return a Promise, which is very intriguing. (I am new to js, ​​and I have never been exposed to promises in the wild before).

First of all, this newly returned Promise is not the original Promise;

Second, the change in the status of this newly returned Promise (whether it is resolve() or reject().) is related to the status of the previous Promise and the way then() is used.

First explain the situation of then(): (similar to catch)

var p1 = Promise.resolve("Success");
var p2 = p1.then(task1);
var p3 = p2.then(task2);

Note: The above task1 and task2 are both callbacks.

Here, p1 is a created Promise and resolved() directly;

p2 is a Promise obtained by using then(), and p3 is also a Promise obtained by using then().

So how does the status of p2 change? What about p3?

I am going to use the following picture to explain this concept:

Among them,

1. The octagon represents a Promise object.

2. The circle represents the internal state of a Promise, and the black arrow represents state changes.

3. The right arrow represents calling the then function.

4. In other words, as long as the then function is called, a new Promise object will be generated.

5. When calling the then function, I don’t know what the status of the previous Promise object is, is it pending or settled? This cannot be assumed and cannot be seen from the outside world.

6. The call of the then function will not block, that is to say, p2 and p3 are generated almost instantly, even if p1 is still slowly migrating its own state.

We know that the status of p1 is resolved (see the code above). However, it has not been explained here how the status of p2 and p3 changes. Is it resolved or rejected? Check out the new image below.

You can see more diamond shapes.

The diamond represents the callback function passed in when calling then. The upward diamond represents the incoming processing [for the previous Promise object that was resolved], and the downward diamond represents the incoming processing [for the previous Promise object that was rejected].

Note: In this example, there is no rejection processing. That is to say, the downward rhombus should not be drawn in the above picture. It is drawn here for convenience. We only need to know that the upward and downward rhombus is specific to us. How to use then or catch. Take another look at the sample code:

<span>var</span> p1 = Promise.resolve("Success"<span>);</span><span>var</span> p2 =<span> p1.then(task1);//产生了向上的菱形</span><span>var</span> p3 = p2.then(task2);//产生了向上的菱形

可以看出,then 的 第二個參數我們沒有給出,也就是我們沒有處理 reject 的情況。

補充一句,如果想要處理 reject 可以使用 then ,也可以使用 catch,catch專門用來處理 reject ,除此之外,和 then 沒有區別。

1. 如果 p1 的最終狀態(resolve 或 reject)被正確處理(當呼叫 then 時,傳入了對應的 callback,也就是有對應的菱形)了,那麼 p2 的狀態就會轉為 resolve。

2. 如果p1 的最終狀態(resolve 或reject)沒有被正確處理(調用then 時,缺少了對應的callback,也就是沒有對應的菱形),那麼p1 的狀態就會路由到p2(接收p1的狀態).

3. 如此傳遞下去。

4. 本文不講解,如何在 callback 取得上一個 Promise 最終數據,也就是說,數據如何傳遞,這個有很多教程了。

三,以下舉一些例子來總結本文。

圖中 P1的狀態是給定的,resolve或reject,都是自己給定的。目的是推出 P2 和 P3 的最終狀態。

以上是四個獨立的例子,之間沒有聯繫。

X代表P3沒有使用 then 或 catch 函數,也就談不到 針對 resolve或reject 的處理了。

最後,若有錯誤,請及時指正,多謝! ~! ! @~~~

以上這篇深入理解js promise chain就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

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: 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

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools