Skip to content

Commit

Permalink
issue#2609 | Sasha | predictable axios requests
Browse files Browse the repository at this point in the history
- axios requests are not delayed by pre-emptive promise creation by default
- add options to interceptors api ("synchronous" and "runWhen"
- add documentation and unit tests
  • Loading branch information
sashaKorotkov committed Jan 30, 2020
1 parent 7df84a7 commit 952426e
Show file tree
Hide file tree
Showing 9 changed files with 301 additions and 29 deletions.
27 changes: 27 additions & 0 deletions README.md
Expand Up @@ -530,6 +530,33 @@ const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```

When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.

```js
axios.interceptors.request.use(function (config) {
config.headers.test = 'I am only a header!';
return config;
}, null, { synchronous: true });
```

If you want to execute a particular interceptor based on a runtime check,
you can add a `runWhen` function to the options object. The function will be called with the config
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
asynchronous request interceptor that only needs to run at certain times.

```js
function onGetCall(config) {
return config.method === 'get';
}
axios.interceptors.request.use(function (config) {
config.headers.test = 'special get headers';
return config;
}, null, { runWhen: onGetCall });
```

## Handling Errors

```js
Expand Down
65 changes: 55 additions & 10 deletions dist/axios.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/axios.map

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions dist/axios.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/axios.min.map

Large diffs are not rendered by default.

58 changes: 51 additions & 7 deletions lib/core/Axios.js
Expand Up @@ -34,6 +34,8 @@ Axios.prototype.request = function request(config) {
config = config || {};
}

var customAdapter = config.adapter;

config = mergeConfig(this.defaults, config);

// Set config.method
Expand All @@ -45,20 +47,62 @@ Axios.prototype.request = function request(config) {
config.method = 'get';
}

// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
var requestCancelled = config.cancelToken && config.cancelToken.reason;

// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousChain = [];
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}

synchronousChain.push(interceptor.synchronous);

requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});

var synchronousRequestInterceptors = synchronousChain.every(function(interceptor) {
return interceptor === true;
});

var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});

while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
var promise;

if (customAdapter || requestCancelled || !synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];

Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain.concat(responseInterceptorChain);

promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}

return promise;
}

var newConfig = config;
for (var i = 0; i < requestInterceptorChain.length - 1; i += 2) {
var onFulfilled = i;
var onRejected = i + 1;
if (typeof requestInterceptorChain[onFulfilled] === 'function') {
try {
newConfig = requestInterceptorChain[onFulfilled](newConfig);
} catch (error) {
requestInterceptorChain[onRejected](error);
}
}
}

promise = dispatchRequest(newConfig);
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}

return promise;
Expand Down
6 changes: 4 additions & 2 deletions lib/core/InterceptorManager.js
Expand Up @@ -14,10 +14,12 @@ function InterceptorManager() {
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
Expand Down
4 changes: 3 additions & 1 deletion test/specs/adapter.spec.js
@@ -1,7 +1,8 @@
var axios = require('../../index');

describe('adapter', function () {
it('should support custom adapter', function (done) {
it('should support custom adapter (asynchronously)', function (done) {
var promiseResolveSpy = spyOn(window.Promise, 'resolve').and.callThrough();
var called = false;

axios('/foo', {
Expand All @@ -11,6 +12,7 @@ describe('adapter', function () {
});

setTimeout(function () {
expect(promiseResolveSpy).toHaveBeenCalled();
expect(called).toBe(true);
done();
}, 100);
Expand Down

0 comments on commit 952426e

Please sign in to comment.