Home Web Front-end JS Tutorial 6 characteristics of JavaScript asynchronous programming Promise mode_javascript skills

6 characteristics of JavaScript asynchronous programming Promise mode_javascript skills

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

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
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

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.

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

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.

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

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

See all articles