Skip to content

Commit

Permalink
Add cancellation support (fixes #113)
Browse files Browse the repository at this point in the history
  • Loading branch information
not-an-aardvark committed Jun 9, 2016
1 parent 061a6ae commit 418093f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/rp.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,13 @@ request.Request.prototype.init = function RP$initInterceptor(options) {
// Init may be called again - currently in case of redirects
if (isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) {

self._rp_promise = new Bluebird(function (resolve, reject) {
Bluebird.config({cancellation: true});
self._rp_promise = new Bluebird(function (resolve, reject, onCancel) {
self._rp_resolve = resolve;
self._rp_reject = reject;
onCancel(function () {
self.abort();
});
});

self._rp_callbackOrig = self.callback;
Expand Down Expand Up @@ -156,6 +160,7 @@ function expose(methodToExpose, exposeAs) {
expose('then');
expose('catch');
expose('finally');
expose('cancel');

request.Request.prototype.promise = function RP$promise() {
return this._rp_promise;
Expand Down
13 changes: 13 additions & 0 deletions test/spec/request-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ describe('Request-Promise', function () {
} else if (status === 222) {
response.writeHead(status, { 'Content-Type': 'text/html' });
response.end('<html><head></head><body></body></html>');
} else if (status === 503) {
// Send no response at all
return;
} else {
response.writeHead(status, { 'Content-Type': 'text/plain' });
var body = (request.method === 'POST' && JSON.stringify(request.body) !== '{}' ? ' - ' + JSON.stringify(request.body) : '');
Expand Down Expand Up @@ -937,6 +940,16 @@ describe('Request-Promise', function () {

});

it('.cancel() to cancel the Bluebird promise and abort the request', function (done) {

var req = rp('http://localhost:4000/503');

setTimeout(function () {
req.cancel();
}, 10);
req.on('abort', done);
});

});

describe('should handle possibly unhandled rejections', function () {
Expand Down

0 comments on commit 418093f

Please sign in to comment.