From 418093f6eae0f4dca93a9b58f398f8ab5b165d0e Mon Sep 17 00:00:00 2001 From: not-an-aardvark Date: Wed, 8 Jun 2016 20:20:38 -0400 Subject: [PATCH] Add cancellation support (fixes #113) --- lib/rp.js | 7 ++++++- test/spec/request-test.js | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/rp.js b/lib/rp.js index 6da24a9..08e09e7 100644 --- a/lib/rp.js +++ b/lib/rp.js @@ -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; @@ -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; diff --git a/test/spec/request-test.js b/test/spec/request-test.js index c3039c8..987750c 100644 --- a/test/spec/request-test.js +++ b/test/spec/request-test.js @@ -29,6 +29,9 @@ describe('Request-Promise', function () { } else if (status === 222) { response.writeHead(status, { 'Content-Type': 'text/html' }); response.end(''); + } 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) : ''); @@ -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 () {