In this article, we will study the principle of synchronous writing of asynchronous callbacks in koa. Similarly, we will also implement a management function. Yes, we can write asynchronous callback functions through synchronous writing.
1. Callback pyramid and ideal solution
We all know that JavaScript is a single-threaded asynchronous non-blocking language. Asynchronous non-blocking is certainly one of its advantages, but a large number of asynchronous operations will inevitably involve a large number of callback functions. Especially when asynchronous operations are nested, a callback pyramid problem will occur, making the code very poor readability. For example, the following example:
var fs = require('fs'); fs.readFile('./file1', function(err, data) { console.log(data.toString()); fs.readFile('./file2', function(err, data) { console.log(data.toString()); }) })
This example reads the contents of two files successively and prints them. The reading of file2 must be performed after the reading of file1 is completed, so the operation must be performed in the callback function of file1 reading. . This is a typical callback nesting, and there are only two levels. In actual programming, we may encounter more levels of nesting. Such code writing is undoubtedly not elegant enough.
In our imagination, a more elegant way of writing should be a way of writing that looks synchronous but is actually asynchronous, similar to the following:
var data; data = readFile('./file1'); //下面的代码是第一个readFile执行完毕之后的回调部分 console.log(data.toString()); //下面的代码是第二个readFile的回调 data = readFile('./file2'); console.log(data.toString());
This way of writing completely avoids callback hell. In fact, koa allows us to write asynchronous callback functions in this way:
var koa = require('koa'); var app = koa(); var request=require('some module'); app.use(function*() { var data = yield request('http://www.baidu.com'); //以下是异步回调部分 this.body = data.toString(); }) app.listen(3000);
So, what makes koa so magical?
2. Generator cooperates with promise to implement asynchronous callback synchronous writing.
The key point, as mentioned in the previous article, is that generator has an effect similar to "break point". When it encounters yield, it will pause, hand over control to the function after yield, and continue execution when it returns next time.
In the koa example above, not just any object can be used after yield! Must be of a specific type. In the co function, promise, thunk functions, etc. can be supported.
In today’s article, we will use promise as an example to analyze and see how to use generator and promise to achieve asynchronous synchronization.
Let’s still analyze using the first example of reading a file. First, we need to transform the file reading function and encapsulate it into a promise object:
var fs = require('fs'); var readFile = function(fileName) { return new Promise(function(resolve, reject) { fs.readFile(fileName, function(err, data) { if (err) { reject(err); } else { resolve(data); } }) }) } //下面是readFile使用的示例 var tmp = readFile('./file1'); tmp.then(function(data) { console.log(data.toString()); })
Regarding the use of promises, if you are not familiar with it, you can take a look at the syntax in es6. (I will also write an article in the near future to teach you how to use es5 syntax to implement a promise object with basic functions, so stay tuned^_^)
Simply speaking, promise can realize the callback function through promise Write it in the form of .then(callback). But our goal is to cooperate with the generator to truly achieve silky-smooth synchronized writing. How to cooperate? Look at this code:
var fs = require('fs'); var readFile = function(fileName) { return new Promise(function(resolve, reject) { fs.readFile(fileName, function(err, data) { if (err) { reject(err); } else { resolve(data); } }) }) } //将读文件的过程放在generator中 var gen = function*() { var data = yield readFile('./file1'); console.log(data.toString()); data = yield readFile('./file2'); console.log(data.toString()); } //手动执行generator var g = gen(); var another = g.next(); //another.value就是返回的promise对象 another.value.then(function(data) { //再次调用g.next从断点处执行generator,并将data作为参数传回 var another2 = g.next(data); another2.value.then(function(data) { g.next(data); }) })
In the above code, we yield readFile in the generator, and the callback statement code is written in yield The following code is completely synchronous, realizing the idea at the beginning of the article.
After yield, what we get is another.value which is a promise object. We can use the then statement to define the callback function. The content of the function is to return the read data to the generator and continue to let the generator continue to interrupt. Execute everywhere.
Basically, this is the core principle of asynchronous callback synchronization. In fact, if you are familiar with Python, you will know that there is the concept of "coroutine" in Python, which is basically implemented using generators (I would like to doubt the generator of es6 It’s just based on python~)
However, we still execute the above code manually. So just like the previous article, we also need to implement a run function to manage the generator process so that it can run automatically!
3. Let the synchronized callback function run automatically: Writing a run function
If you carefully observe the part of the previous code that manually executes the generator, you can also find a pattern that allows us to directly write a recursive function. Instead: The
var run=function(gen){ var g; if(typeof gen.next==='function'){ g=gen; }else{ g=gen(); } function next(data){ var tmp=g.next(data); if(tmp.done){ return ; }else{ tmp.value.then(next); } } next(); }
function receives a generator and allows the asynchronous execution in it to be executed automatically. Using this run function, we let the previous asynchronous code execute automatically:
var fs = require('fs'); var run = function(gen) { var g; if (typeof gen.next === 'function') { g = gen; } else { g = gen(); } function next(data) { var tmp = g.next(data); if (tmp.done) { return; } else { tmp.value.then(next); } } next(); } var readFile = function(fileName) { return new Promise(function(resolve, reject) { fs.readFile(fileName, function(err, data) { if (err) { reject(err); } else { resolve(data); } }) }) } //将读文件的过程放在generator中 var gen = function*() { var data = yield readFile('./file1'); console.log(data.toString()); data = yield readFile('./file2'); console.log(data.toString()); } //下面只需要将gen放入run当中即可自动执行 run(gen);
执行上述代码,即可看到终端依次打印出了file1和file2的内容。
需要指出的是,这里的run函数为了简单起见只支持promise,而实际的co函数还支持thunk等。
这样一来,co函数的两大功能基本就完整介绍了,一个是洋葱模型的流程控制,另一个是异步同步化代码的自动执行。在下一篇文章中,我将带大家对这两个功能进行整合,写出我们自己的一个co函数!

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
