search
HomeWeb Front-endJS Tutorial6 characteristics of JavaScript asynchronous programming Promise mode_javascript skills

Before we start the formal introduction, we want to see what Javascript Promise looks like:

Copy the code The code is as follows:

var p = new Promise(function(resolve, reject) {
resolve("hello world");
});

p.then(function(str ) {
alert(str);
});

1. then() returns a Forked Promise

What is the difference between the following two pieces of code?

Copy code The code is as follows:

// Exhibit A
var p = new Promise (/*...*/);
p.then(func1);
p.then(func2);

// Exhibit B
var p = new Promise(/ *...*/);
p.then(func1)
.then(func2);

If you take the above two pieces of code seriously, then Promises is just a one-dimensional An array of callback functions. However, this is not the case. Each then() call returns a forked promise. Therefore, in ExhibitA, if func1() throws an exception, func2() is still called normally.

In ExhibitB, if func1() throws an error, fun2() will not be called because the first call returns a new promise, which will be rejected in func1(). The result is that func2() is skipped.

Summary: promises can be forked into multiple paths, similar to complex flow charts.

2. Callback should deliver the result

What warning will you get when you run the following code?

Copy code The code is as follows:

var p = new Promise(function(resolve, reject) {
resolve("hello world");
});

p.then(function(str) {})
.then(function(str) {
alert (str);
});

The alert in the second then() does not display anything. This is because the callback function, in the context of the promise, does not have a callback function because the result changes. The promise expects your callback function to return the same result or a replacement result, which is then passed to the next callback function.

Similarly use adpater to change the results, as follows:

Copy the code The code is as follows:

var feetToMetres = function(ft) { return ft*12*0.0254 };

var p = new Promise(/*...*/);

p.then(feetToMetres)
.then(function(metres) {
alert(metres);
});

3. Only exceptions from the upper layer can be caught

What is the difference between these two pieces of code?

Copy code The code is as follows:

// Exhibit A
new Promise(function( resolve, reject) {
resolve("hello world");
})
.then(
function(str) {
throw new Error("uh oh");
},
undefined
)
.then(
undefined,
function(error) {
alert(error);
}
);

// Exhibit B
new Promise(function(resolve, reject) {
resolve("hello world");
})
.then(
function(str) {
throw new Error("uh oh");
},
function(error) {
alert(error);
}
);


in In the first piece of code, the exception thrown in the first then() will be caught by the second then(), and then the "uh oh" warning will be triggered. This follows that only exceptions from the previous level will be caught.

In the second piece of code, the callback function and the error callback function are at the same level, which means that when an exception is thrown in the callback, it will not be caught. In fact, the error callback in the second code will only be thrown when the promise is rejected or the promise itself fails

4. Errors can be recovered

In an error callback function, if you do not rethrow the error, the promise will assume that you have recovered from the error and reverse to the resolved state. In the next example, "i'm saved" will be displayed because the error callback in the first then() did not rethrow the exception.

Copy code The code is as follows:

var p = new Promise(function(해결, 거부) {
거절(new Error("pebkac"));
});

p.then(
정의되지 않음,
function(error) { }
)
.then(
function(str) {
Alert("저는 구원받았습니다!");
},
function(error) {
Alert("Bad Computer!");
}
);

Promise는 양파 위에 겹겹이 쌓인 것이라고 생각하면 됩니다. 각각의 then()은 양파에 또 다른 레이어를 추가합니다. 각 수준은 처리 중인 활동을 나타냅니다. 레이어가 끝나면 결과는 복구되어 다음 레이어를 위한 준비가 된 것으로 간주됩니다.

5. 약속은 일시중지될 수 있습니다

then() 메서드에서 실행할 준비가 되었다고 해서 다른 메서드를 일시 중지하고 미리 실행할 수 없다는 의미는 아닙니다. 현재 Promise를 일시 중지하거나 다른 Promise가 완료될 때까지 기다리게 하려면 then()에서 다른 Promise를 반환하면 됩니다.

코드 복사 코드는 다음과 같습니다.

var p = new Promise(/*. ..* /);

p.then(function(str) {
if(!loggedIn) {
return new Promise(/*...*/);
}
})
.then(function(str) {
Alert("Done.");
})

이전 코드에서는 프롬프트가 다음까지 표시되지 않습니다. 새로운 약속이 해결되었습니다. 이는 기존 비동기 코드 경로에 더 많은 종속성을 도입하는 편리한 방법입니다. 예를 들어, 사용자 세션이 시간 초과된 것을 발견하고 이전 코드 경로를 계속하기 전에 두 번째 로그인을 초기화할 수 있습니다.

6. 해결된 약속은 즉시 실행되지 않습니다.

다음 코드를 실행하면 프롬프트 상자가 표시되나요?

코드 복사 코드는 다음과 같습니다.

function runme() {
var i = 0 ;

new Promise(function(resolve) {
resolve();
})
.then(function() {
i = 2;
});
Alert(i);
}

Promise가 즉시 해결되고 then() 메서드가 즉시 실행되므로 프롬프트 2가 감지될 것이라고 생각할 수 있습니다. 그러나 Promise 정의에서는 모든 호출이 강제로 비동기화되도록 요구합니다. 따라서 수정되기 전에 프롬프트가 생성됩니다.
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