Home  >  Article  >  Web Front-end  >  An in-depth analysis of the 'onion model' in Nodejs

An in-depth analysis of the 'onion model' in Nodejs

青灯夜游
青灯夜游forward
2021-05-07 10:29:554094browse

This article will take you through the "onion model" in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of the 'onion model' in Nodejs

Currently the more popular Node.js frameworks include Express, KOA and Egg.js, followed by another emerging TypeScript-related framework - Nest.js. No matter which Node.js framework it is, it is implemented based on middleware, and the execution method of middleware (can be understood as a class or function module) needs to be based on the onion model

Recommended learning: "nodejs tutorial

1. Onion model

We all know that onions are wrapped one layer at a time, layer by layer, but now we are not looking at its three-dimensional structure, but It is necessary to cut the onion. From the cutting plane, as shown in the picture:

An in-depth analysis of the onion model in Nodejs

You can see that in order to pass through the center of the onion, you must first The onion skin is penetrated layer by layer into the center point, and then the skin is penetrated outward layer by layer from the center point. There is a characteristic here: how many layers of skin are penetrated when entering, how many layers of skin must be penetrated when exiting. . Penetrating the epidermis first and then exiting it conforms to the principle of what we call a stack list, first in, last out.

2. The relationship between the onion model and Node

The more popular Node.js frameworks currently include Express, KOA and Egg.js. No matter which Node.js framework it is, it is based on middleware To achieve, the execution method of middleware (can be understood as a class or function module) needs to be based on the onion model

We can think of the skin of the onion as middleware:

The process from the outside to the inside is the keyword next();

, while the process from the inside to the outside means that after each middleware is executed, it enters the original upper layer of middleware, all the way to the outermost layer.

3. Execution of middleware

Taking express as an example, the following is a basic execution process of middleware:

An in-depth analysis of the onion model in NodejsAn in-depth analysis of the onion model in Nodejs

Koa is the next generation node framework developed by the same team based on Express. The main difference between the two is:

  • Express encapsulates and has a lot of built-in middleware, such as connect and router, while KOA is relatively lightweight, and developers can customize the framework according to their own needs;
  • Express is based on callback to handle middleware, while KOA is based on await/async;
  • In When executing middleware asynchronously, Express does not strictly follow the onion model to execute middleware, but KOA strictly follows it (reflecting that the two processes will be different when the middleware is an asynchronous function).

Introduction to the differences between Express and KOA regarding the execution of the onion model:

We retain the original three of the above example code middleware, and insert a new asynchronous middleware between 2 and 3. The code is as follows:

(1) express

/**
 * 异步中间件
 */
app.use(async (req, res, next) => {
    console.log('async');
    await next();
    await new Promise(
        (resolve) => 
            setTimeout(
                () => {
                    console.log(`wait 1000 ms end`);
                    resolve()
                }, 
            1000
        )
    );
    console.log('async end');
});

and then Other middlewares are modified to await next() method, as shown in the following middleware 1 method:

/**
 * 中间件 1
 */
app.use(async (req, res, next) => {
    console.log('first');
    await next();
    console.log('first end');
});

Rerun, the final output result is:

An in-depth analysis of the onion model in Nodejs

You can see Out, it is normal to call from outside to inside, and calls are made layer by layer. When going from inside to outside, some changes occur. The main reason is that asynchronous middleware does not output execution results in order.

(2) KoaKeep the above code sequence and only change the corresponding express syntax to koa syntax. The middleware 1 and asynchronous middleware code parts are as follows:

const Koa = require('koa');
const app = new Koa();
/**
 * 中间件 1
 */
app.use(async (ctx, next) => {
    console.log('first');
    await next();
    console.log('first end');
});
/**
 * 异步中间件
 */
app.use(async (ctx, next) => {
    console.log('async');
    await next();
    await new Promise(
        (resolve) => 
            setTimeout(
                () => {
                    console.log(`wait 1000 ms end`);
                    resolve()
                }, 
            1000
        )
    );
    console.log('async end');
});

Rerun, the final output result is:

An in-depth analysis of the onion model in Nodejs

You will find that KOA strictly follows the execution of the onion model, from top to bottom, That is, from the inside of the onion to the outside, output first, second, async, and third; then output third end, async end, second end, and first end from the inside to the outside.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of An in-depth analysis of the 'onion model' in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete