首页 文章

koa:promise vs async等待中间件

提问于
浏览
1

我正在尝试编写一个Koa中间件,如果 condition met ,请转到下一个middelware . 如果 condition unmet ,则短路流量 . 我找到了两种方法,使用promise或async / await .

Method 1: Promise-based

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

Method 2: Async/Await

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

这两种方法之间有 any difference 吗?如果没有, which one is preferred

1 回答

  • 1

    await next() 之后没有代码时,你会实现同样的目标 . 正如ippi在评论中提到的那样,之后有代码时,等待将只是"cleaner",因为它会等到承诺解决到下一行,而在"common promises way"中你必须处理承诺的解决方案 . 在您的具体示例中,它没关系,但可能在您的代码的其他部分,您将使用其中一个(可能在另一个中间件?),并且您将希望同化您的代码 .

    如果你以后会有一些东西你会这样做(可能你已经知道):

    async functions (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');
        }
    });
    

    Common function

    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编码的人来说,原始承诺看起来更好......

相关问题