search
HomeWeb Front-endJS TutorialBased on es6: asynchronous process control idea

Based on es6: asynchronous process control idea

Jun 26, 2017 am 09:10 AM
javascriptjspromiseaccomplishSimplespecification

——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        })
    });
});

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});

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(){
        
    }
}

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

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则是失败态
  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;
    }
 
 Deferred =.promise = =   self =  promise =((handler = promise.queue.shift())){ (handler && res = handler.fulfilled.apply(self,args); (res && res.isPromise){ res.queue ==

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

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); //调用完成态回调函数                
                
            }
        }
    }
}

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!

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.