From 3fcf54ff361d4563445e295212c362d5b1e6c518 Mon Sep 17 00:00:00 2001 From: Nick Uraltsev Date: Mon, 17 Oct 2016 18:20:13 -0700 Subject: [PATCH] Fixing issue with calling cancel after response has been received --- lib/adapters/http.js | 4 ++++ lib/adapters/xhr.js | 4 ++++ test/specs/cancel.spec.js | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/lib/adapters/http.js b/lib/adapters/http.js index 95e4e8c..5d6c7f9 100644 --- a/lib/adapters/http.js +++ b/lib/adapters/http.js @@ -188,6 +188,10 @@ module.exports = function httpAdapter(config) { if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { + if (aborted) { + return; + } + req.abort(); reject(cancel); aborted = true; diff --git a/lib/adapters/xhr.js b/lib/adapters/xhr.js index 1fb890b..1174a86 100644 --- a/lib/adapters/xhr.js +++ b/lib/adapters/xhr.js @@ -156,6 +156,10 @@ module.exports = function xhrAdapter(config) { if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } + request.abort(); reject(cancel); // Clean up request diff --git a/test/specs/cancel.spec.js b/test/specs/cancel.spec.js index d02d8e3..bb84baf 100644 --- a/test/specs/cancel.spec.js +++ b/test/specs/cancel.spec.js @@ -63,4 +63,27 @@ describe('cancel', function() { }); }); }); + + describe('when called after response has been received', function() { + // https://github.com/mzabriskie/axios/issues/482 + it('does not cause unhandled rejection', function (done) { + var source = CancelToken.source(); + axios.get('/foo', { + cancelToken: source.token + }).then(function () { + window.addEventListener('unhandledrejection', function () { + done.fail('Unhandled rejection.'); + }); + source.cancel(); + setTimeout(done, 100); + }); + + getAjaxRequest().then(function (request) { + request.respondWith({ + status: 200, + responseText: 'OK' + }); + }); + }); + }); });