How did Koa implement the onion model without async await?

Mondo Technology Updated on 2024-03-07

In noasync/await, KOA implements the onion model by using ES6's generator function. Specifically, the koa middleware function is a piece with anextThe parameter generator function is called when the middleware function is callednextmethod, 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 nextIndicates that the current execution is suspended and the next middleware function is executed. Let's say we have two middleware functionsmiddleware1withmiddleware2, their ** are as follows:

function* middleware1(next) function* middleware2(next)
We can use itcomposefunctions combine them into an onion model:

scsscopy codeconst compose = require('koa-compose');const app = compose([middleware1, middleware2]);app();
In this example,composeThe function willmiddleware1withmiddleware2into 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 end
As you can see, this result is consistent with the characteristics of the onion model.

Related Pages