Home Web Front-end JS Tutorial What are the asynchronous programming methods in javascript?

What are the asynchronous programming methods in javascript?

Apr 19, 2019 pm 01:07 PM
javascript Asynchronous programming

Methods for implementing asynchronous programming in JavaScript include: callback methods that are easy to understand and implement but difficult to maintain code, publish/subscribe methods, event listening methods that are easy to understand and can bind multiple events but have confusing workflow, and Promises methods

Asynchronous mode is very important, long-running operations on the browser side should be executed asynchronously to avoid unresponsiveness. Next, I will introduce the implementation of asynchronous programming methods in JavaScript in detail in the article. It has a certain reference effect and I hope it will be helpful to everyone.

What are the asynchronous programming methods in javascript?

【Recommended course: JavaScript Tutorial

Everyone knows that the execution environment of JavaScript is single-threaded. Single-threading means that only one task can be run at any time. If you encounter multiple tasks, you need to wait in the queue for the completion of the previous task. Therefore, it takes a lot of time. The synchronous mode is similar to this single-threaded mode. The asynchronous mode is completely different. Each task has a callback function. When a task is completed, it will execute the callback function, and subsequent tasks can be The previous task runs simultaneously. The execution order of tasks is different from the sequence of tasks in the queue.

Method 1: Callback method

This method is the basic method of asynchronous programming. Suppose there are two functions f1 and f2, the latter will wait for the first function result.

F1(); 
F2();
Copy after login

If f1 is a long-running operation, you can override f1 and use f2 as the callback function of f1.

function f1(callback){
setTimeout(function () {
 callback();
    }, 1000);
}
Copy after login

Using this mode, synchronous operations can be converted into asynchronous operations. f1 will not prevent program execution. It will execute the main logic first and then perform time-consuming operations.

The callback function The advantage is that it is easy to understand and implement, but the disadvantage is that the code is unreadable and maintainable, different components are highly coupled, the workflow is very confusing, and each task can only have one callback function.

Method 2: Publish/Subscribe

This event can be understood as a signal. Assuming there is a signal center, if a task is completed, it will publish a signal to the signal center, and other Tasks can receive specified signals from subscribed signal centers. This approach is called the publish/subscribe pattern or the observer pattern.

Example: f2 subscribes to the signal center to complete the signal

jQuery.subscribe(“done”,f2);
Copy after login

Then write f1 as

function f1(){
    setTimeout(function () {
     jQuery.publish("done");
    }, 1000);
}
Copy after login

jQuery.publish("done") means when f1 When it completes execution it will send a completion signal to the signal center and then f2 will start execution.

When f2 completes execution, it can unsubscribe.

jQuery.unsubscribe(“done”,f2);
Copy after login

Method Three: Event Listening

Another method is the event-driven model. The execution of a task does not depend on the code sequence. They wait for an event to occur. Still using f1 and f2 in this example, first bind an event to f1.

f1.on('done',f2);
Copy after login

The meaning of the above code is that if the f1 completion event occurs, f2 will be executed.

function f1(){
    setTimeout(function () {
      f1.trigger('done');
    }, 1000);
}
Copy after login

f1.trigger('done') means it will trigger the done event and then execute f2 when the execution is complete.

The advantage is that it is easy to understand and can bind multiple events, each event can have many callback functions, and it can decouple which is beneficial to modularity. The disadvantage is that the entire program will be event-driven and the workflow is not very clear.

Method 4: Promises method

The Promises object is a standard proposed by CommonJS to provide a common interface for asynchronous programming. Each asynchronous task returns a Promises object, which has a then method that allows setting a callback function. For example, the callback function f2 of f1:

F1().then(F2)
Copy after login

f1 should be written as:

function f1(){
    var dfd = $.Deferred();
    setTimeout(function () {
        dfd.resolve();
    }, 500);
    return dfd.promise;
}
Copy after login

The advantage is that the callback functions are linked, the workflow of the program is very clear, and it has a set Complete linking methods that can be used to implement powerful functionality.

For example, setting up multiple callback functions:

f1().then(f2).then(f3);
Copy after login

Another example, if there is an error:

f1().then(f2).fail(f3);
Copy after login

One advantage that the other three methods do not have is that once one is completed Task, if you add more callback functions, they will be executed immediately. The disadvantage is that it is not easy to understand.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone.

The above is the detailed content of What are the asynchronous programming methods in javascript?. For more information, please follow other related articles on the PHP Chinese website!

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

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.

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

What are the advantages and disadvantages of asynchronous programming in PHP? What are the advantages and disadvantages of asynchronous programming in PHP? May 06, 2024 pm 10:00 PM

The advantages of asynchronous programming in PHP include higher throughput, lower latency, better resource utilization, and scalability. Disadvantages include complexity, difficulty in debugging, and limited library support. In the actual case, ReactPHP is used to handle WebSocket connections, demonstrating the practical application of asynchronous programming.

Python asynchronous programming: Reveal the essence of asynchronous programming and optimize code performance Python asynchronous programming: Reveal the essence of asynchronous programming and optimize code performance Feb 26, 2024 am 11:20 AM

Asynchronous programming, English Asynchronous Programming, means that certain tasks in the program can be executed concurrently without waiting for other tasks to complete, thereby improving the overall operating efficiency of the program. In Python, the asyncio module is the main tool for implementing asynchronous programming. It provides coroutines, event loops, and other components required for asynchronous programming. Coroutine: Coroutine is a special function that can be suspended and then resumed execution, just like a thread, but a coroutine is more lightweight and consumes less memory than a thread. The coroutine is declared with the async keyword and execution is suspended at the await keyword. Event loop: Event loop (EventLoop) is the key to asynchronous programming

See all articles