Why is everyone using Koa instead of Express? Koa, as we all know, was built by the original Express team to become a smaller, more expressive, and more robust Web development framework.

Express has its own built-in middleware and implements its own routing, but Koa is a lightweight framework that does not have its own built-in middleware and routing, but inherits third-party middleware, which is somewhat different from Express.

What exactly is the difference between Express and KOA’s middleware?

Koa solves the asynchrony problem, so let’s start with a small example:

This is an example of implementing multiple middleware runs with KOA and Express, and after the first middleware execution, there is an asynchronous function that needs to be processed.

See the examples:

let express = require('express');
let app = express();
function log() {
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
        resolve('I am the result of asynchronous success to be executed');
    }, 1000);
})
}
app.use(async(req,res,next) => {
    console.log(1);
await next();
console.log(2);
})
app.use(async(req, res, next) => {
    console.log(3);
    let r = await log(a); console.log(r); next(); console.log(4); }) app.use((req, res, next) => { console.log(5); next(); console.log(6); }) app.listen(3000);Copy the code

Express middleware next function implementation method:

function app() {
}
app.routes = [];
app.use = function (fn) {
  app.routes.push(fn);
}
function log() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('I am the result of asynchronous success to be executed');
    }, 1000);
  })
}
app.use(async (req, res, next) => {
  console.log(1);
  await next(); 
  console.log(2);
})
app.use(async (req, res, next) => {
  console.log(3);
  let r = await log(a); console.log(r); next(); console.log(4); }) app.use((req, res, next) => { console.log(5); next(); console.log(6); })let index = 0;
function next() {
  if (app.routes.length === index) return
  let route = app.routes[index++];
  route({}, {}, () => next());
}
next();
Copy the code

The results are as follows:

1 3 2 I am the result of asynchronous success 5 6 4Copy the code

In the same way, let’s look at the basic koA method and the implementation rationale for next:

let Koa = require('koa');
let app = new Koa();
function log() {
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
            resolve('I am the result of asynchronous success to be executed'); }, 1000); }) } app.use(async(ctx,next)=>{ console.log(1); // The second intermediate may have asynchronous logic, we want the first middleware to wait for the second middleware to finish and then continue to await next(); console.log(2); }); app.use(async (ctx, next) => { console.log(3);let r = await log(a); console.log(r); next(); console.log(4); }); app.use((ctx, next) => { console.log(5); next(); console.log(6); }); app.listen(3000);Copy the code

Comments:

  • 1. In the first middleware, if a promise is waiting, the rest will be executed after the promise is executed. If undefined is returned, the next person will not be executed after the promise is executed.
  • 2. Koa has a feature: middleware internally processes it to make promises;
function app() {
}
app.routes = [];
app.use = function (fn) {
  app.routes.push(fn);
}
function log() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('I am the result of asynchronous success to be executed');
    }, 1000);
  })
}
app.use(async (req, res, next) => {
  console.log(1);
  await next(); 
  console.log(2);
})
app.use(async (req, res, next) => {
  console.log(3);
  let r = await log(a); console.log(r); next(); console.log(4); }) app.use((req, res, next) => { console.log(5); next(); console.log(6); })let index = 0;
function next() {
  if (app.routes.length === index) return
  letroute = app.routes[index++]; // KoA has a feature: the middleware handles it internally to make promisesreturn route({}, {}, () => next());
}
next();
Copy the code

The execution result is as follows:

1 3 I am the result of asynchronous success to execute 5 6 4 2Copy the code

Conclusion:

As can be seen from the above examples:

  • Express middleware does not wait for the next middleware to complete
  • Koa will wait for the next intermediate to complete
  • Koa solves the asynchronous problem