In noasync/await
, KOA implements the onion model by using ES6's generator function. Specifically, the koa middleware function is a piece with anext
The parameter generator function is called when the middleware function is callednext
method, it suspends the current execution, moves on to the next middleware function until the last middleware function is executed, and then returns the execution rights to the previous middleware function and continues to execute the following **. This process is like peeling off an onion layer by layer, hence the name onion model.
Here's a simple koa middleware function implemented using a generator function:
function* mymiddleware(next)In this middleware function,
yield next
Indicates that the current execution is suspended and the next middleware function is executed. Let's say we have two middleware functionsmiddleware1
withmiddleware2
, their ** are as follows:
function* middleware1(next) function* middleware2(next)We can use it
compose
functions combine them into an onion model:
scsscopy codeconst compose = require('koa-compose');const app = compose([middleware1, middleware2]);app();In this example,
compose
The function willmiddleware1
withmiddleware2
into a single functionapp
, and then call this function to execute the entire middleware chain. The result of the execution is as follows:
sqlcopy codemiddleware1 startmiddleware2 startmiddleware2 endmiddleware1 endAs you can see, this result is consistent with the characteristics of the onion model.