diff --git a/index.js b/index.js index 66db73d..5af2eee 100644 --- a/index.js +++ b/index.js @@ -11,6 +11,22 @@ var eosConfig = { error: false, }; +function rethrowAsync(err) { + process.nextTick(rethrow); + + function rethrow() { + throw err; + } +} + +function tryCatch(fn, args) { + try { + return fn.apply(null, args); + } catch (err) { + rethrowAsync(err); + } +} + function asyncDone(fn, cb) { cb = once(cb); @@ -21,18 +37,18 @@ function asyncDone(fn, cb) { function done() { d.removeListener('error', onError); d.exit(); - return cb.apply(null, arguments); + return tryCatch(cb, arguments); } function onSuccess(result) { - tick(done, null, result); + done(null, result); } function onError(error) { if (!error) { error = new Error('Promise rejected without Error'); } - tick(done, error); + done(error); } function asyncRunner() { diff --git a/package.json b/package.json index 96ef96d..027b285 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "jscs": "^2.3.5", "jscs-preset-gulp": "^1.0.0", "mocha": "^2.4.5", + "pumpify": "^1.3.6", "rx": "^4.0.6", "through2": "^2.0.0", "when": "^3.7.3" diff --git a/test/promises.js b/test/promises.js index eaa0264..edaa8e4 100644 --- a/test/promises.js +++ b/test/promises.js @@ -48,6 +48,7 @@ describe('promises', function() { var d = domain.create(); d.once('error', function(err) { expect(err).toExist(); + expect(err.message).toContain('Boom'); done(); }); d.run(function() { diff --git a/test/streams.js b/test/streams.js index 6cacc5e..a0eed97 100644 --- a/test/streams.js +++ b/test/streams.js @@ -5,6 +5,7 @@ var expect = require('expect'); var fs = require('fs'); var path = require('path'); var through = require('through2'); +var pumpify = require('pumpify'); var asyncDone = require('../'); @@ -29,6 +30,21 @@ function failure() { return read.pipe(new EndStream()); } +function withErr(chunk, _, cb) { + cb(new Error('Fail')); +} + +function pumpifyError() { + var read = fs.createReadStream(exists); + var pipeline = pumpify( + through(), + through(withErr), + through() + ); + + return read.pipe(pipeline); +} + function unpiped() { return fs.createReadStream(exists); } @@ -48,6 +64,14 @@ describe('streams', function() { }); }); + it('should handle an errored pipeline', function(done) { + asyncDone(pumpifyError, function(err) { + expect(err).toBeAn(Error); + expect(err.message).toNotBe('premature close'); + done(); + }); + }); + it('handle a returned stream and cb by only calling callback once', function(done) { asyncDone(function(cb) { return success().on('end', function() {