Home > Web Front-end > JS Tutorial > Based on es6: asynchronous process control idea

Based on es6: asynchronous process control idea

零下一度
Release: 2017-06-26 09:10:04
Original
1427 people have browsed it

——Based on es6: Promise/A+ specification and simple implementation of asynchronous process control ideas

Foreword:

The powerful asynchronous processing capability of nodejs makes it a great choice on the server side It's brilliant, and the number of applications based on it continues to increase, but the nested and difficult-to-understand code brought about by asynchrony makes nodejs not look so elegant and bloated. Code similar to this:

function println(name,callback){var value = {"ztf":"abc","abc":"def","def":1}
    setTimeout(function(){
        callback(value[name]);
    },500);
}

println("ztf",function(name){ 
    println(name,function(res){
        console.log(res);//def        println(res,function(res1){
            console.log(res1);//1        })
    });
});
Copy after login

The value object is defined in println of the above code, and callback is called with a delay of five hundred seconds to pass in the relevant value.

First call println Pass in "ztf", assuming that the next execution function depends on the value returned this time, then the call becomes the above code. Pass in ztf and return abc, use abc to return def, use def to return 1;

Because nodejs is used as a server, various database queries are indispensable. Database queries have more dependencies. For example, if I need to query the permissions of a certain user, then three steps are required

 ① Through id Find the user

 ② Find the corresponding role through the returned user role id

  ③ Find the corresponding permission through the role

Three levels of nesting relationships are needed here, and the code is also It’s almost the same as above.

promise/A+ specification

Promise represents the final result of an asynchronous operation. It has three states, namely unfinished state, completed state (resolve), failed state (reject) The state is irreversible, the completed state cannot return to uncompleted, and the failed state cannot become completed state

 

The main way to interact with promise is to pass in the callback function in its then method to form a chain call,

 

 

Implementation

First let’s look at how the Promise/A+ specification is called in specific applications:

We can change the above example to:

based on the promise specification:
var  printText = function(name){var deferred = new Deferred(); //new一个托管函数println(name,deferred.callback());//把回调函数托管到Deferred中实现return deferred.promise; //返回promise对象实现链式调用}

printText("ztf")
.then(function(name){
    console.log(name);return printText(name); //第二次调用依赖第一次调用 返回promise对象  在成功态中判断
})
.then(function(res){
    console.log(res);//defreturn printText(res);
})
.then(function(res1){
    console.log(res1);//1});
Copy after login

To a certain extent, this kind of code changes the status quo of continuous nesting of asynchronous code. Through the chain call of the then() method, the process control of the asynchronous code is achieved.

//处理回调var Promise = function(){this.queue = []; //存储的是回调函数的队列this.isPromise = true; 
}//延迟对象var Deferred = function(){this.promise = new Promise();
}
Deferred.prototype = {//托管了callback回调函数    callback:function(){
        
    },//完成态    resolve:function(){
        
    },//失败态    reject:function(){
        
    }
}
Copy after login

Two objects are defined here, Promise and Deferred. Promise is responsible for processing the distribution of functions. Deferred, as its name implies, handles delayed objects.

 Promise =.queue = []; .isPromise = = handler =((fulfilledHandler) == =((errorHandler) == =  Deferred =.promise = =
Copy after login

You can see that the Promise.then method just inserts the callback into the queue, one is executed in the completion state and the other is executed in the failure state.

In order to complete the entire process, it is also necessary to define the processing method of completion state and failure state in Deferred:

//处理内部操作var Promise = function(){this.queue = []; //存储的是回调函数的队列this.isPromise = true; 
}
Promise.prototype = {//then方法 fulfilledHandler是完成态时执行的回调函数 errorHandler则是失败态
Copy after login
  then:function(fulfilledHandler,errorHandler){
        var handler = {};
        if(typeof(fulfilledHandler) == "function"){
            handler.fulfilled = fulfilledHandler;
        }
        if(typeof(errorHandler) == "function"){
            handler.errored = errorHandler;
        }
     this.queue.push(handler);
        return this;
    }
Copy after login
 
 Deferred =.promise = =   self =  promise =((handler = promise.queue.shift())){ (handler && res = handler.fulfilled.apply(self,args); (res && res.isPromise){ res.queue ==
Copy after login

The completion state operation is added, and this code obtains .then the callback function set passed in promise.queue while is called in sequence, passing in the current arguments

Then we need to put the completion state in the managed callback function (Deferred.callback()) and execute it according to the logic:

 Promise =.queue = []; .isPromise = = handler =((fulfilledHandler) == =((errorHandler) == =  Deferred =.promise = = self =  args = Array.prototype.slice.call(arguments); = args.concat(Array.prototype.slice.call(arguments,));  self =  promise = args =((handler = promise.queue.shift())){ (handler && res = handler.fulfilled.apply(self,args); (res && res.isPromise){ res.queue ==
Copy after login

The code is here. The main functions have been completed, but the failure state has not been added. Its implementation is similar to the success state except that it lacks secondary nesting:

//处理内部操作var Promise = function(){this.queue = []; //存储的是回调函数的队列this.isPromise = true; 
}
Promise.prototype = {//then方法 fulfilledHandler是完成态时执行的回调函数 errorHandler则是失败态    then:function(fulfilledHandler,errorHandler){var handler = {};if(typeof(fulfilledHandler) == "function"){
            handler.fulfilled = fulfilledHandler;
        }if(typeof(errorHandler) == "function"){
            handler.errored = errorHandler;
        }this.queue.push(handler);return this;
    }
}//处理外部操作var Deferred = function(){this.promise = new Promise();
}
Deferred.prototype = {//托管了callback回调函数    callback:function(){var self = this;var args = Array.prototype.slice.call(arguments); //将arguments转为数组return function(err){if(err){//这里是失败态  传入了error对象                self.reject.call(self,err);return;
            }
            args = args.concat(Array.prototype.slice.call(arguments,1)); //合并外部arguments 与内部arguments 去掉err//这里是完成态            console.log(args);
            self.resolve.apply(self,args);
            
        }
    },//完成态    resolve:function(){var self = this;var promise = self.promise;var args = arguments;var handler;        while((handler = promise.queue.shift())){ //取出待执行队列中的第一个函数 直到全部执行完毕if(handler && handler.fulfilled){var res = handler.fulfilled.apply(self,args); //调用失败态回调函数if(res && res.isPromise){ //如果有二次嵌套 则再次执行promiseres.queue = promise.queue;
                    self.promise = res;return;
                }
            }
        }
    },//失败态    reject:function(err){var self = this;var promise = self.promise;var args = arguments;var handler;while((handler = promise.queue.shift())){ //取出待执行队列中的第一个函数 直到全部执行完毕if(handler && handler.errored){                var res = handler.fulfilled.call(self,err); //调用完成态回调函数                
                
            }
        }
    }
}
Copy after login

Summary

Key points:
① Each operation returns the same promise object, ensuring chain operations

② Function callback One parameter is always an error object. If there is no error, it is null

 ③ Each chain is connected through the then method and returns the promise object to be executed again

The above is the detailed content of Based on es6: asynchronous process control idea. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template