Analyze issues with the koa middleware mechanism in node
This article mainly introduces the detailed explanation of the koa middleware mechanism in node, and introduces koa and compatibility issues in detail. It has certain reference value. Those who are interested can learn more
koa
koa is a smaller, more expressive, and more robust web framework created by the original team of express.
In my eyes, koa is indeed much lighter than express. koa feels more like a middleware framework to me. koa is just a basic shelf. When you need to use the corresponding functions, use Just implement it with corresponding middleware, such as routing system, etc. A better point is that express is processed based on callbacks. As for how bad callbacks are, you can search and see by yourself. koa1 is based on the co library, so koa1 uses Generator instead of callbacks, and koa2 uses async/await due to node's support for async/await. Regarding async and co libraries, you can refer to an article I wrote before (Understanding async). Koa can be said to be a shelf for various middlewares. Let’s take a look at koa’s implementation of the middleware part:
koa1’s middleware
koa1 mainly uses It is implemented by Generator. Generally speaking, a middleware of koa1 probably looks like this:
app.use(function *(next){ console.log(1); yield next; console.log(5); }); app.use(function *(next){ console.log(2); yield next; console.log(4); }); app.use(function *(){ console.log(3); });
The output will be 1, 2, 3, 4 , 5. The implementation of koa's middleware mainly relies on koa-compose:
function compose(middleware){ return function *(next){ if (!next) next = noop(); var i = middleware.length; // 组合中间件 while (i--) { next = middleware[i].call(this, next); } return yield *next; } } function *noop(){}
The source code is very simple, and the function is to connect all the middleware together. First, pass a noop to the penultimate middleware as its next, and then pass the sorted penultimate middleware as next to the penultimate middleware. The final next is the sorted first middleware. pieces. It's more complicated to say, but let's look at it by drawing:
The effect achieved is as shown in the picture above, which is similar to the goal that redux needs to achieve. As long as the yield next is encountered, the next intermediate will be executed. It is easy to connect this process in series using the co library. Let’s briefly simulate the complete implementation of the middleware:
const middlewares = []; const getTestMiddWare = (loggerA, loggerB) => { return function *(next) { console.log(loggerA); yield next; console.log(loggerB); } }; const mid1 = getTestMiddWare(1, 4), mid2 = getTestMiddWare(2, 3); const getData = new Promise((resolve, reject) => { setTimeout(() => resolve('数据已经取出'), 1000); }); function *response(next) { // 模拟异步读取数据库数据 const data = yield getData; console.log(data); } middlewares.push(mid1, mid2, response); // 简单模拟co库 function co(gen) { const ctx = this, args = Array.prototype.slice.call(arguments, 1); return new Promise((reslove, reject) => { if (typeof gen === 'function') gen = gen.apply(ctx, args); if (!gen || typeof gen.next !== 'function') return resolve(gen); const baseHandle = handle => res => { let ret; try { ret = gen[handle](res); } catch(e) { reject(e); } next(ret); }; const onFulfilled = baseHandle('next'), onRejected = baseHandle('throw'); onFulfilled(); function next(ret) { if (ret.done) return reslove(ret.value); // 将yield的返回值转换为Proimse let value = null; if (typeof ret.value.then !== 'function') { value = co(ret.value); } else { value = ret.value; } if (value) return value.then(onFulfilled, onRejected); return onRejected(new TypeError('yield type error')); } }); } // 调用方式 const gen = compose(middlewares); co(gen);
koa2’s middleware
With node's support for async/await, it seems that there is no need to resort to tool libraries like co. Just use the native ones directly, so koa has also made changes. Let's take a look at the current koa -compose:
function compose (middleware) { // 参数检验 return function (context, next) { // last called middleware # let index = -1 return dispatch(0) function dispatch (i) { if (i <= index) return Promise.reject(new Error('next() called multiple times')) index = i let fn = middleware[i] // 最后一个中间件的调用 if (i === middleware.length) fn = next if (!fn) return Promise.resolve() // 用Promise包裹中间件,方便await调用 try { return Promise.resolve(fn(context, function next () { return dispatch(i + 1) })) } catch (err) { return Promise.reject(err) } } } }
koa-compose uses Promise. The parameters of koa2's middleware have also changed from one to two, and the middleware that executes the next one uses await. next(), to achieve the same effect as the above sample code, you need to change the way the middleware is written:
const middlewares = []; const getTestMiddWare = (loggerA, loggerB) => async (ctx, next) => { console.log(loggerA); await next(); console.log(loggerB); }; const mid1 = getTestMiddWare(1, 4), mid2 = getTestMiddWare(2, 3); const response = async () => { // 模拟异步读取数据库数据 const data = await getData(); console.log(data); }; const getData = () => new Promise((resolve, reject) => { setTimeout(() => resolve('数据已经取出'), 1000); }); middlewares.push(mid1, mid2); // 调用方式 compose(middlewares)(null, response);
How to achieve compatibility
It can be seen that koa1 and koa2 still have many differences in the implementation of middleware. If you use the middleware of koa1 directly under koa2, there will definitely be errors. How to make these two versions compatible? It has also become a problem. The koa team has written a package that is a middleware for koa1 that can be used in koa2. It is called koa-convert. Let’s first take a look at how to use this package:
function *mid3(next) { console.log(2, 'koa1的中间件'); yield next; console.log(3, 'koa1的中间件'); } convert.compose(mid3)
Let’s take a look at the idea of implementing this package:
// 将参数转为数组,对每一个koa1的中间件执行convert操作 convert.compose = function (arr) { if (!Array.isArray(arr)) { arr = Array.from(arguments) } return compose(arr.map(convert)) } // 关键在于convert的实现 const convert = mw => (ctx, next) => { // 借助co库,返回一个Promise,同时执行yield return co.call(ctx, mw.call(ctx, createGenerator(next))); }; function * createGenerator (next) { /* next为koa-compomse中: function next () { return dispatch(i + 1) } */ return yield next() // 执行完koa1的中间件,又回到了利用await执行koa2中间件的正轨 }
Personally feel that the idea of koa-convert is to encapsulate a layer of Promise for Generator so that the previous middleware can Use the await next() method to call, and use the co library for the execution of Generator to achieve compatibility.
The above is the detailed content of Analyze issues with the koa middleware mechanism in node. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version
