Created
March 18, 2015 15:35
-
-
Save mzabriskie/ec3a25dd45dfa0de92c2 to your computer and use it in GitHub Desktop.
axios abort request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The problem with using Promises for a request API is that Promises | |
* make it difficult to abort the request. Typically when using XHR | |
* some factory will wrap the actual XHR, but ultimately will return | |
* the XHR object. | |
* | |
* ``` | |
* var request = performRequest('/user/12345'); | |
* request.abort(); | |
* ``` | |
* | |
* Using Promises, the Promise is what's returned. | |
* | |
* ``` | |
* var promise = performRequest('/user/12345'); | |
* promise.then((response) => { console.log(response); }); | |
* ``` | |
* | |
* How then can the request be aborted? | |
* | |
* Working on axios (https://github.com/mzabriskie/axios), | |
* I get a lot of requests (no pun intended) for how to | |
* handle aborting a request once it's been made. This is | |
* a potential workaround for aborting a request when using | |
* XHR with Promises. | |
*/ | |
// Setup request config and initiate the request | |
var config = { | |
method: 'get', | |
url: '/user/12345' | |
}; | |
axios(config); | |
// Internally axios will add a requestID property to the | |
// request config. This is an auto incrementing integer | |
// that is unique to the request. | |
console.log(config); // {method: 'get', url: '/user/12345', requestID: 0} | |
// Now the request can be aborted by passing the requestID | |
// to axios.abort. Behind the scenes axios will have a | |
// collection of requests indexed by requestID. The request | |
// can then be aborted if it hasn't already been fulfilled. | |
// This is very similar to how setTimeout/clearTimeout works. | |
axios.abort(config.requestID); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mzabriskie Any updates on this, interested to.
abort()
isn't an option in the latest,cancelPreviousRequest
would be useful. I know the latest supports cancelTokens now but they don't work for me.