Skip to content

Commit

Permalink
Automatically clean up after an error is thrown (#31)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
Richienb and sindresorhus authored Mar 17, 2021
1 parent 66e464a commit d859280
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ const writeStream = async (filePath, data) => pipeline(data, fs.createWriteStrea
const createTask = (tempyFunction, {extraArguments = 0} = {}) => async (...arguments_) => {
const [callback, options] = arguments_.slice(extraArguments);
const result = await tempyFunction(...arguments_.slice(0, extraArguments), options);
const returnValue = await callback(result);
await del(result, {force: true});
return returnValue;

try {
return await callback(result);
} finally {
await del(result, {force: true});
}
};

module.exports.file = options => {
Expand Down
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ test('.file.task()', async t => {
t.false(await pathExists(temporaryFilePath));
});

test('.task() - cleans up even if callback throws', async t => {
let temporaryDirectoryPath;
await t.throwsAsync(tempy.directory.task(async temporaryDirectory => {
temporaryDirectoryPath = temporaryDirectory;
throw new Error('Catch me if you can!');
}), {
instanceOf: Error,
message: 'Catch me if you can!'
});

t.false(await pathExists(temporaryDirectoryPath));
});

test('.directory()', t => {
const prefix = 'name_';

Expand Down

0 comments on commit d859280

Please sign in to comment.