Skip to content

Commit

Permalink
fix: prevent callback from triggering twice when callback throws
Browse files Browse the repository at this point in the history
closes #542
  • Loading branch information
privatenumber committed May 14, 2021
1 parent c8aae18 commit 6db755d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/__tests__/volume/callback-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
jest.useFakeTimers('modern');

// Fixes https://github.com/streamich/memfs/issues/542
it('should throw error instead of callback', () => {
const { Volume } = require('../../volume');
const vol = new Volume();

vol.writeFile('/asdf.txt', 'asdf', 'utf8', (err) => {
if (!err) {
throw new Error('try to trigger catch');
}
});

expect(() => jest.runAllTimers()).toThrow('try to trigger catch');
});
5 changes: 4 additions & 1 deletion src/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,11 +826,14 @@ export class Volume {
private wrapAsync(method: (...args) => void, args: any[], callback: TCallback<any>) {
validateCallback(callback);
setImmediate(() => {
let result;
try {
callback(null, method.apply(this, args));
result = method.apply(this, args);
} catch (err) {
callback(err);
return;
}
callback(null, result);
});
}

Expand Down

0 comments on commit 6db755d

Please sign in to comment.