javascript - koa:promise vs async await 中间件

标签 javascript node.js express koa koa2

我正在尝试编写一个 Koa 中间件,如果条件满足,则转到下一个中​​间件。如果条件未满足,则将流程短路。我找到了 2 种方法,使用 promise 或 async/await。

方法 1:基于 promise

app.use(function(ctx, next){
    // if condition met 
    if (conditionMet){
        ctx.somedata = 'bar';
        // go to next middleware
        return next();
    }
})

方法 2:异步/等待

app.use(async function(ctx, next){
    // if condition met 
    if (conditionMet){
        ctx.somedata = 'bar';
        // go to next middleware
        await next();
    }
})

这两种方法之间有任何区别吗?如果没有,首选哪个

最佳答案

await next() 之后没有代码时,您可以实现相同的目的。正如 ippi 在评论中提到的那样,当之后有代码时, with await 只会“更干净”,因为它会等到 promise 解决后转到下一行,而在“共同 promise 方式”中你必须处理决议的 promise 。在您的特定示例中,这无关紧要,但您可能会在代码的其他部分使用一个或另一个(也许在另一个中间件中?),并且您会想要使代码同质化。

万一你之后会有什么东西,你会这样做(可能你已经知道):

异步函数( Node v7.6+)

app.use(async (ctx, next) => {
    // if condition met 
    if (conditionMet){
        ctx.somedata = 'bar';
        // go to next middleware
        await next();
        // after code
        console.log('this will be executed after promise next() is resolved');
    }
});

常用函数

app.use((ctx, next) => {
    // if condition met 
    if (conditionMet){
        ctx.somedata = 'bar';
        // go to next middleware
        return next().then(() => {
            // after code
            console.log('this will be executed after promise next() is resolved');
        });
      }
});

我不能说有更好的,它们只是不同而已。对我来说,async/await 看起来更简洁,我个人可以更好地控制代码流并避免 Promises Hell。我认为它们变得越来越强大并且得到了新的 javascript 标准的支持,但是对于开始使用 js 编码的人来说,原始的 promises 看起来更好......

关于javascript - koa:promise vs async await 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50892664/

相关文章:

node.js - 在node.js gm上绘制西里尔文字

python - 使用 Eve 和 AngularJS 的 CORS 问题

node.js - 在 ExpressJs 中设置 Cookie 失败

node.js - 通过 mongoose 连接到 MongoDB 会出现 auth failed 错误

javascript - 如何更改范围 slider 以显示金钱?

javascript - 由于某种原因在 native react 中渲染后发生 ComponentWillMount

javascript - JS - 根据计算禁用下拉选项

javascript - Uncaught Error : Configuration must contain `projectId` ( when using environment variable )

javascript - Node : route try to send response two times - ERR_HTTP_HEADERS_SENT ('set' ); error

javascript - 当不在页面顶部时滚动到顶部按钮显示