Skip to content

Commit

Permalink
Fixed race condition on immediate requests cancellation (#4261)
Browse files Browse the repository at this point in the history
* Fixes #4260: fixed race condition on immediate requests cancellation

* Update http.js

Co-authored-by: Jay <jasonsaayman@gmail.com>
  • Loading branch information
DigitalBrainJS and jasonsaayman committed May 9, 2022
1 parent 27280ec commit de48c5d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/cancel/CancelToken.js
Expand Up @@ -25,10 +25,9 @@ function CancelToken(executor) {
this.promise.then(function(cancel) {
if (!token._listeners) return;

var i;
var l = token._listeners.length;
var i = token._listeners.length;

for (i = 0; i < l; i++) {
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
Expand Down
28 changes: 28 additions & 0 deletions test/unit/adapters/http.js
Expand Up @@ -1166,6 +1166,34 @@ describe('supports http with nodejs', function () {
});
});

it('should able to cancel multiple requests with CancelToken', function(done){
server = http.createServer(function (req, res) {
res.end('ok');
}).listen(4444, function () {
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
var canceledStack = [];

var requests = [1, 2, 3, 4, 5].map(function(id){
return axios
.get('/foo/bar', { cancelToken: source.token })
.catch(function (e) {
if (!axios.isCancel(e)) {
throw e;
}

canceledStack.push(id);
});
});

source.cancel("Aborted by user");

Promise.all(requests).then(function () {
assert.deepStrictEqual(canceledStack.sort(), [1, 2, 3, 4, 5])
}).then(done, done);
});
});

it('should allow passing FormData', function (done) {
var form = new FormData();
var file1= Buffer.from('foo', 'utf8');
Expand Down

0 comments on commit de48c5d

Please sign in to comment.