JS 避免在多个位置使用相同的 if 语句

JS Avoid same if statement in multiple locations

我有一个 function 处理大量 JSON 文档并将它们 insertsMongoDB

我想 log 此函数在多个位置执行的操作,然后将有效负载发送到 S3。但是,这是被调用者的条件。

function doStuffWithJSON(options={}) {
    const apiRes = getJSONFromAPI();

    if (options.logAndChuck) { console.log('we got results successfully') }

    //50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { console.log('we did stuff with the result') }

    //Another 50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { sendJsonToS3(apiRes) }
}

这里的重复模式是我在函数的多个不同位置有相同的 if 语句。鉴于它的性质,不确定是否有任何方法可以避免这种情况。

想知道是否有任何模式可以像这样清理东西。

谢谢!

将问题评论中的建议转化为代码:

function doStuffWithJSON(options={}) {
    const apiRes = getJSONFromAPI();

    logAndChuck('we got results successfully')

    //50 lines of code that are unconditionally being executed

    logAndChuck('we did stuff with the result')

    //Another 50 lines of code that are unconditionally being executed

    if (options.logAndChuck) { sendJsonToS3(apiRes) }
}

function logAndChuck(options, message) {
    if (options.logAndChuck) { console.log(message) }
}

这真的取决于 - 恕我直言,多次使用简单的 if 语句不是问题。但是,如果它更复杂,您可以为此创建一个函数 - 在本地函数范围内或以上采用回调函数:

function doStuffWithJSON(options={}) {
    const exec = (callbackFn) => {
        if (options.logAndChuck) {
            callbackFn();
        }
    };

    const apiRes = getJSONFromAPI();

    exec(() => console.log('we got results successfully'));

    //50 lines of code that are unconditionally being executed

    exec(() => console.log('we did stuff with the result'));

    //Another 50 lines of code that are unconditionally being executed

    exec(() => sendJsonToS3(apiRes));
}