首页 > 解决方案 > 重构此函数以一致地使用“return”

问题描述

我有一个 JS 函数,我收到 eslint 错误,因为重构此函数以始终使用“return”。但看起来我总是回来。有人可以建议我如何解决这个问题吗?

function filterBooks(books, context, purpose, callback) {
    if (!context && !purpose) {
        logger.warn("context and purpose not found so ingnoring the filtering on context and purpose");
        return callback(null, books);
    } else {
        if (purpose) {
            filterBooksByPurpose(books, purpose);
        }
        if (context) {
                filterBooksByContext(books, context,function(err,books){
                if(err){
                    return callback(err, null);
                }else{
                    books = removebooksEmptyPages(books);
                    return callback(null, books);
                }
            });
        }
    }
}

标签: node.jscallbackeslint

解决方案


else块没有任何返回值,但该if块有,这就是 linter 抱怨的原因。在下面的代码块中注释

function filterBooks(books, context, purpose, callback) {
    if (!context && !purpose) {
        logger.warn("context and purpose not found so ingnoring the filtering on context and purpose");
        return callback(null, books);
    } else {
        // *********** no return value in this block
        if (purpose) {
            filterBooksByPurpose(books, purpose);
        }
        if (context) {
                // there is no return here as well, the callback function has return value but not for filterBooks
                filterBooksByContext(books, context,function(err,books){
                if(err){
                    return callback(err, null);
                }else{
                    books = removebooksEmptyPages(books);
                    return callback(null, books);
                }
            });
        }
    }
}

推荐阅读