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); });
var result=ajax(url); setTimeout(function(result){ console.log(result); },400);
ajax(url0,function(result0){ ajax(result0.url1,function(result1){ ajax(result1.url2,function(result2){ console.log(result2); }); }); });
(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); });
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(); } ]);
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!