Home Web Front-end JS Tutorial Detailed explanation of usage examples of callback functions and managers in javascript asynchronous programming

Detailed explanation of usage examples of callback functions and managers in javascript asynchronous programming

Jul 21, 2017 pm 02:31 PM
javascript js Manager

Based on the browser's event polling mechanism (and the event polling mechanism in Node.js), JavaScript often runs in an asynchronous environment. Due to the characteristics of the JavaScript language itself (which does not require programmers to control threads/processes), it is very important to solve asynchronous programming in js. It can be said that in a complete project, it is impossible for js developers not to face asynchronous operations.

1. Callback function

(1) Classic callback function method: nested inline function

Suppose we have an ajax() method that receives a url parameter, initiates an asynchronous request to the address, and executes the second parameter - a callback function at the end of the request:


##

ajax(url,function(result){
 console.log(result);
});
Copy after login

It can be said that this method is the callback function method used by almost every front-end developer. With such a callback mechanism, developers do not need to write code similar to the following to speculate when the server request will return:


var result=ajax(url);
setTimeout(function(result){
 console.log(result);
},400);
Copy after login

Everyone should be able to understand what I want to express here. We set a timer with a delay of 400 milliseconds, assuming that the ajax request we make will be completed within 400 milliseconds. Otherwise, we will operate on an undefined result.


But there is a problem that gradually emerges as the project expands: if the scene requires us to have multiple layers of nested callback functions, the code will become difficult to read and maintain:


ajax(url0,function(result0){
 ajax(result0.url1,function(result1){
  ajax(result1.url2,function(result2){
   console.log(result2);
  });
 });
});
Copy after login

(2) Calling external functions

In order to solve the code confusion problem exposed by inline callback functions, we introduce external function calls to solve similar problems:


function handle2(result){
 console.log(result);
}
function handle1(result){
 ajax(result.url,function(result){
  handle2(result);
 });
}
ajax(url,function(result){
 handle1(result);
});
Copy after login

This optimization method of splitting inline functions to call external functions can greatly maintain the simplicity of the code.

2. Develop a callback manager

Observing popular JavaScript process control tools, such as Nimble, Step, and Seq, we will learn a simple design pattern: The asynchronous JavaScript execution process is controlled through the callback manager. The following is a typical key code example of the callback manager:


var Flow={};
//设置next方法,在上一个方法完成时调用下一个方法
Flow.next=function(){
 if(this.stack[0]){
  //弹出方法栈中的第一个方法,并执行他
  this.stack.shift()();
 }
};
//设置series方法,接收一个函数数组,并按序执行
Flow.series=function(arr){
 this.stack=arr;
 this.next();
};

//通过Flow.series我们能够控制传入的函数的执行顺序
Flow.series([
  function(){
   //do something
   console.log(1);
   Flow.next();
  },
  function(next){
   //do something
   console.log(2);
   Flow.next();
  }
]);
Copy after login

We initialized a Flow controller and provided it with Two function attributes, series and next, are designed. Within the business method we wrote, the next method is sequentially triggered by calling Flow.next() at the end of the method; asynchronous functions are sequentially executed by executing the series method. This way of managing asynchronous function calls through the core controller simplifies our programming process, allowing developers to devote more energy to business logic.

The above is the detailed content of Detailed explanation of usage examples of callback functions and managers in javascript asynchronous programming. 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)

High CPU usage of Feature Access Manager service in Windows 11 High CPU usage of Feature Access Manager service in Windows 11 Feb 19, 2024 pm 03:06 PM

Some PC users and gamers may experience abnormally high CPU usage when using Windows 11 or Windows 10, especially when running certain applications or games. This article provides some suggestions to help users alleviate this problem. Some affected PC users noted that when experiencing this issue, they observed Task Manager showing other applications using only 0% to 5% of the CPU, while the Service Host: Capability Access Manager service was seeing usage as high as 80%. % to 100%. What is the Service Host: Feature Access Manager service? The function of the Function Access Manager service is to confirm whether the application has permission to access the camera and microphone and grant the necessary permissions. It facilitates the management of UWP applications

Find out if your PC has a Neural Processing Unit (NPU) in Windows 11 Find out if your PC has a Neural Processing Unit (NPU) in Windows 11 Mar 16, 2024 pm 06:34 PM

NPU is the abbreviation of neural processing unit, which is a processor specially used to perform calculations such as machine learning algorithms. Simply put, it is a processor specifically designed to accelerate tasks related to artificial intelligence. This article will explain how to check whether a Windows 11 PC is equipped with a Neural Processing Unit (NPU). Find out if your PC has a Neural Processing Unit (NPU) in Windows 11 The following methods will help you determine if your PC has a Neural Processing Unit (NPU) installed in Windows 11. Via Task Manager Via Device Manager By visiting the official website Below, we have explained all these methods in detail. 1] Use Task Manager to check if your PC has NPU on Windows 11 PC

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to set up the microphone in realtek high-definition audio manager How to set up the microphone in realtek high-definition audio manager Jan 02, 2024 am 09:33 AM

The win10 system is a system that can carry out various settings and adjustments. Today, the editor brings you the solution on how to set the microphone in realtek high-definition audio manager! If you are interested, come and take a look. How to set the microphone in realtek high-definition audio manager: 1. Find the "realtek high-definition audio manager" icon in the show hidden icons in the lower left corner of the desktop. 2. Click to enter the interface. The first thing you see is the "Speaker Page". In this interface, you can adjust the speaker sound through speaker configuration. 3. Next is the sound effect. You can choose the sound effect environment you want as well as "equalizer, pop, rock, club" and so on. 4. Next is the indoor sound quality correction. Indoor space correction can only correct the "

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

See all articles