gpt4 book ai didi

javascript - Koa中,中间件中的await next()、return await next()、return next()、next()有什么区别?

转载 作者:行者123 更新时间:2023-12-01 01:06:50 29 4
gpt4 key购买 nike

文档概述了在中间件中使用“await next()”的用例,导致中间件暂停并触发下游的下一个中间件,直到所有中间件都执行完毕,此时上游级联将开始并且中间件将完整执行。如果用户想要缩短级联,那么单独写“return”就会将级联全部切断。

我不明白的是,如果用户返回以下内容之一会发生什么:

const exampleMiddleware1 = async (ctx, next) => {
return await next();

console.log('Doing something');
};

const exampleMiddleware2 = async (ctx, next) => {
next();

console.log('Doing something');
};

const exampleMiddleware3 = async (ctx, next) => {
return next();

console.log('Doing something');
};

在第一个例子中,我认为它会暂停,触发下一个中间件,但不会完成向上级联的执行。

在第二个例子中,我认为下一个中间件将与console.log一起触发,我认为它不会向上触发,也许?

在第三个例子中,我认为下一个中间件会被触发,但它不会触发向上级联的控制台日志,与第一个例子相同。

我的想法正确吗?我正在编写一个 koa 应用程序,想了解更多有关它的限制的信息,但我发现我不太了解这一领域。

最佳答案

exampleMiddleware1exampleMiddleware3 是相同的(不需要返回 await 除非你想在返回之前捕获错误)

  • 你的console.log永远不会被调用

示例中间件2

  1. 如果下一个中间件返回 promise

    • 您的 console.log 将调用,而无需等待下一个中间件完成
  2. 如果下一个中间件返回 promise

    • 它将完成下一个中间件,然后是 console.log

关于javascript - Koa中,中间件中的await next()、return await next()、return next()、next()有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55551939/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com