VueRouter: runQueue

Over the past week or so I have been analyzing VueRouter’s source code, where I encountered the runQueue function.

The route guard has three parameters to,from, and next. Next is the second argument (callback function) passed by fn below, and only after this callback is executed will the guards in the queue be traversed one by one.

The role of middleware

Isolate the details between infrastructure and business logic. Details can be found in Node.js P210

Another common image is the onion ring model. This diagram visually illustrates the relationship between the outer infrastructure and the core business logic.

Express middleware

The middleware principles of Express were analyzed earlier in the article Express Middleware Principles: juejin.cn/post/684490…

A simplified version of middleware has also been refined.

VueRouter’s middleware is actually very similar to Express. Both store the navguard/middleware function in an array, iterate through the array, and use next to execute the next navguard/middleware function. The latter is more comfortable using a while loop, but exposes a global index. The former is the index inside the function.

In addition, because they are recursive calls, hence the emergence of the onion ring model.

Beggar Edition Express middleware

Change the runQueue

Here I remove the cb that fn(iterator) executes after the queue is iterated.

Iterator is wrapped around the original guard function. This is just breaking up the envelope. And iterator calls next(to). To be honest, the value of to will not be called, and it will not be useful to put here.

Juejin. Cn/post / 687347…

Analysis of Koa middleware principle

The only thing not analyzed here is the Koa middleware, which is commented in detail here. Koa, as the new generation framework, certainly supports the Promise writing. Koa’s middleware is based on this.

This is also done recursively, passing Dispatch as a recursive function to a user-defined middleware function.

Unlike express and VueRouter navigation guards, koA middleware only accepts CTX and Next. In fact, the KOA framework does one layer of processing. Similarly, if Next is never called, the request will not reach the core business logic.

In addition, compose below returns an anonymous function that takes a next parameter, which does the same thing as cb in VueRouter’s runQueue: cb/next is executed after all the functions in the array have been executed.

In the end, KOA’s middleware actually uses promises, and there’s nothing special about it.

conclusion

VueRouter/ Express/KOa’s execution logic essentially completes all functions in the queue asynchronously. Koa wrapped a layer of Promise in the middleware function.