callback-return
Require return when calling a callback
Calling a callback doesn't stop the function. If you call callback(err) in an if and forget to return, the code below it runs too, and the callback often gets called a second time.
The rule reports a call to callback, cb or next inside a function, unless the call is returned, is followed by a return that ends its block, or is the function's last statement.
ESLint has deprecated this rule. Use n/callback-return instead.
Examples#
function load(path, callback) {
readFile(path, (err, text) => {
if (err) {
callback(err)Expected return with your callback function.;
}
callback(null, JSON.parse(text));
});
}function load(path, callback) {
readFile(path, (err, text) => {
if (err) {
return callback(err);
}
callback(null, JSON.parse(text));
});
}
function check(request, response, next) {
if (!request.user) {
next(new Error("Not signed in"));
return;
}
next();
}Options#
The only option is the list of names that count as callbacks. It replaces the default, ["callback", "cb", "next"]. A name can be a path such as "response.send".
["done", "response.send"]1 problemfunction handle(request, response) {
if (!request.user) {
response.send(401)Expected return with your callback function.;
}
response.send(200);
}With the same list, callback isn't checked anymore:
["done", "response.send"]No problemsfunction load(err, callback) {
if (err) {
callback(err);
}
finish();
}When not to use it#
The rule only looks at the name, so it can't tell a callback from any other function called next. You don't need it in code that uses promises and async functions.