【问题标题】:How to avoid repeated code in promise chain?如何避免promise链中的重复代码?
【发布时间】:2023-04-02 10:50:02
【问题描述】:

我有一个承诺链:

Promise
.then(function() {
    if (some condition) {
        Promise.reject("Request cancelled");
    }

    return doSomething1();
})
.then(function() {
    if (some condition) {
        Promise.reject("Request cancelled");
    }

    return doSomething2();
})
.then(function() {
    if (some condition) {
        Promise.reject("Request cancelled");
    }

    return doSomething3();
})
.catch(function(err) {
    if (err == "Request cancelled") {
        // err handling here
    }
})

在每个 .then() 中,都有相同的代码检查是否破坏承诺链:

// repeated code
if (some condition) {
    Promise.reject("Request cancelled");
}

我需要这样做,因为我想在发现错误后立即停止其余的异步调用,以便应用程序可以节省一些内存和时间。但它看起来真的很凌乱和多余。

所以我的问题是:有没有办法编写这段代码并避免重复代码?

谢谢!

【问题讨论】:

    标签: promise coding-style code-cleanup


    【解决方案1】:

    如果您不打算将此逻辑构建到 doSomething1()doSomething2() 中,以便在满足条件时它们自己返回一个被拒绝的承诺,那么我能想到的最简单的事情就是改变这个:

    p.then(function() {
        if (some condition) {
            Promise.reject("Request cancelled");
        }
    
        return doSomething1();
    }).then(function() {
        if (some condition) {
            Promise.reject("Request cancelled");
        }
    
        return doSomething2();
    }).then(...).catch(...);
    

    到这样的事情:

    p.then(checkCondition).then(function() {
        return doSomething1().then(checkCondition);
    }).then(function() {
        return doSomething2().then(checkCondition);
    }).then(...).catch(...);
    

    在哪里,您定义 checkCondition() 以在其中包含您的共享条件:

    function checkCondition(val)
        if (some condition) {
            return Promise.reject("Request cancelled");
        }
        return val;
    }
    

    或者你可以包装你的承诺返回函数:

    p.then(checkCondition).then(function() {
        return checkCondition(doSomething1());
    }).then(function() {
        return checkCondition(doSomething2());
    }).then(...).catch(...);
    

    checkCondition() 是这样的:

    function checkCondition(p) {
        return p.then(function(val) {
            if (some condition) {
                return Promise.reject("Request cancelled");
            }
            return val;
        });
    }
    

    如果真的只是对这些异步函数调用进行排序并检查它们的特定条件,那么您可以通过传入一个函数数组并对数组排序,检查每个结果的条件,从而使这一切自动化。

    【讨论】:

    • 非常感谢! :) 我会试试看
    • @Max - 如果这回答了您的问题,您可以通过单击答案左侧的复选标记向社区表明这一点。遵循正确的程序,这也将为您赢得一些声誉积分。
    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 2020-08-31
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多