Async Callback Invoked Twice
Quick summary
Your function called the callback for both the success and error paths — the caller receives two completions and runs its logic twice.
Why this happens
Calling the callback in both an if and an else branch without returning
Firing the callback after a timeout even though the success path already fired it
Forgetting a guard flag so retries re-invoke the original callback
Minimal example
function load(cb) {
if (Math.random() > 0.5) cb(null, 'data');
cb(new Error('fail')); // always called!
}
load((err, d) => console.log(err, d)); // logs twicefunction load(cb) {
if (Math.random() > 0.5) return cb(null, 'data');
cb(new Error('fail'));
}
load((err, d) => console.log(err, d)); // logs onceWithout a return, the success branch calls cb and then execution falls through to the error cb, invoking the callback twice. Adding return ensures only one call.
How to diagnose
Add a log at the top of the callback to count how many times it runs
Check every code path in the producing function for missing return after callback
Use a wrapper that throws if the callback is called more than once
How to fix
Return immediately after every callback invocation
Guard with a
let called = falseflag and ignore subsequent callsRestructure so there is exactly one callback call per function execution
How to prevent
Always return right after invoking a callback
Use Promises which can only settle once, instead of raw callbacks