Skip to content

Commit

Permalink
Do not wrap all callbacks in promise
Browse files Browse the repository at this point in the history
Promise will swallow exceptions in callback

Closes sindresorhus/got#84
  • Loading branch information
floatdrop committed Jul 18, 2015
1 parent e08f34a commit e3e4e90
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 19 deletions.
43 changes: 25 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,36 @@ module.exports = function read(stream, options, cb) {

if (options.encoding === undefined) { options.encoding = 'utf8'; }

var promise = new Promise(function (resolve, reject) {
var sink = new BufferStream();
var promise;

sink.on('finish', function () {
var data = Buffer.concat(this.buffer, this.length);

if (options.encoding) {
data = data.toString(options.encoding);
}
if (!cb) {
var resolve, reject;
promise = new Promise(function(_res, _rej) {
resolve = _res;
reject = _rej;
});

cb = function (err, data) {
if (err) { return reject(err); }
resolve(data);
});
};
}

stream.once('error', reject);
var sink = new BufferStream();

stream.pipe(sink);
});
sink.on('finish', function () {
var data = Buffer.concat(this.buffer, this.length);

if (!cb) {
return promise;
}
if (options.encoding) {
data = data.toString(options.encoding);
}

promise.then(function (data) {
cb(null, data);
}, cb);
};
});

stream.once('error', cb);

stream.pipe(sink);

return promise;
}
27 changes: 26 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global it */
/* global describe, before, it, after */

'use strict';
var assert = require('assert');
Expand Down Expand Up @@ -86,3 +86,28 @@ it('should return Promise', function (done) {
done();
}, done);
});

describe('uncaughtException', function () {
before(function () {
this.listeners = process.listeners('uncaughtException');
process.removeAllListeners('uncaughtException');
});

it('should not swallow errors in callback', function (done) {
var stream = new Readable();
stream.push(null);

read(stream, function() {
throw new Error('uncaughtException');
});

process.on('uncaughtException', function (err) {
assert.equal(err.message, 'uncaughtException');
done();
});
});

after(function () {
this.listeners.forEach(process.on.bind(process, 'uncaughtException'));
});
});

0 comments on commit e3e4e90

Please sign in to comment.