重构此函数以一致地使用“返回”

时间:2019-01-14 07:09:37

标签: node.js callback eslint

我有一个JS函数,但由于存在jslin错误,因此请重构此函数以始终使用“返回”。但是看起来我总是在回去。有人可以建议我如何解决这个问题吗?

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);
                }
            });
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

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);
                }
            });
        }
    }
}

答案 1 :(得分:0)

此linter规则解决了函数返回不一致的问题,它通常表示错误或代码异味。

如果<?xml …是同步的,则它应该一致地返回结果,或者提供副作用(修改filterBooks)而没有返回。如果books是异步的,则无法同步返回结果。

filterBooks是节点样式的错误优先回调。它们通常在异步代码中使用,并且异步函数无法从异步调用的回调中返回值。

callback似乎是同步的,因此使用回调是不合理的。

如果当前用作:

filterBooks

可以将其重构为:

filterBooks(..., (err, result) => {
  if (err)
    console.error(err);
  else
    console.log(result);
});

使用中的其他功能也可以使用,例如try { const result = filterBooks(...); console.log(result); } catch (err) { console.error(err); }

相关问题