question 1: why is the middleware in the koa2 framework written in the form of async, rarely in Synchronize mode (that is, without async)? For example,
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
after looking up some materials, I can see that in Ruan Yifeng"s koa tutorial, there is an example of Synchronize writing:
const one = (ctx, next) => {
console.log(">> one");
next();
console.log("<< one");
}
const two = (ctx, next) => {
console.log(">> two");
next();
console.log("<< two");
}
const three = (ctx, next) => {
console.log(">> three");
next();
console.log("<< three");
}
app.use(one);
app.use(two);
app.use(three);
/*
output:
>> one
>> two
>> three
<< three
<< two
<< one
*/
there is no async at all. Nguyen only mentioned later: "so far, the middleware in all examples is Synchronize, without asynchronous operations." If there are asynchronous operations (such as reading a database), the middleware must be written as an async function. "
then look for information and find that the next of koa2 middleware returns promise, because the dispatch (i) in the source code returns promise, so I have another question,
question 2: why is it designed to return promise? Can"t you achieve the effect of middleware concatenation without returning promise? Because the execution of middleware is a Synchronize process in understanding, how to understand it when designed asynchronously?
question 3: is there a lot of async function in the code written in koa2 (the company project code is full of async, do you also need async when returning the output json?) ? Are there any scenarios or examples that don"t need to write async?