【问题标题】:Refactor this function to use "return" consistently重构此函数以一致地使用“return”
【发布时间】:2019-01-14 16:23:01
【问题描述】:

我有一个 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);
                }
            });
        }
    }
}

【问题讨论】:

  • filterBooks 的消费者是否曾经使用过返回值? (看起来不像,因为传递了回调?如果没有,只需删除所有returns)
  • @certainPerformance 它对我有用。谢谢
  • @CertainPerformance 你能帮我理解一下回调的情况,什么时候返回,什么时候不返回。
  • 如果函数传递了一个回调,并且回调总是在最后被调用,那么这个函数可能不应该返回任何东西——任何需要回传的数据都可以通过回调发送.
  • 您似乎在不适合的地方使用了回调。未显示 filterBooksByContext。也是同步的吗?那就不要使用回调了。

标签: node.js callback eslint


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    如果filterBooks 是同步的,它应该始终返回结果或提供副作用(修改books)而不返回。如果filterBooks是异步的,则无法同步返回结果。

    callback 是 Node 风格的错误优先回调。它们常用于异步代码中,异步函数不能从异步调用的回调中返回值。

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

    其他功能也可以使用,例如filterBooksByContext

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2010-11-08
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 2020-06-30
      • 2013-02-24
      相关资源
      最近更新 更多