Table of Contents
Foreword:
promise/A+ specification
Implementation
Summary
Home Web Front-end JS Tutorial Based on es6: asynchronous process control idea

Based on es6: asynchronous process control idea

Jun 26, 2017 am 09:10 AM
javascript js promise accomplish Simple specification

——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!

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

The easiest way to query the hard drive serial number The easiest way to query the hard drive serial number Feb 26, 2024 pm 02:24 PM

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

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

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles