Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed race condition on immediate requests cancellation #4261

Merged
merged 5 commits into from May 9, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So smart! I've tested it with my cases, it works 🔥

token._listeners[i](cancel);
}
token._listeners = null;
Expand Down
27 changes: 27 additions & 0 deletions test/unit/adapters/http.js
Expand Up @@ -1034,5 +1034,32 @@ 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);
});
});
});