【发布时间】: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。也是同步的吗?那就不要使用回调了。