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
  • Loading branch information
streamich committed Aug 31, 2021
2 parents 1716968 + 6db755d commit 07e8215
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 07e8215

Please sign in to comment.