0

I have an axios call that I cancel, this is then caught using catch to display a message.

After this, I have chained a then(), but then() is called even if I cancel the request.

How can I make it so that then() is called only if the request is not cancelled?

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

-1

Your question is hard to answer without much context. But if I understand you correctly I think what you are looking for is to delay the axios request and wait a few seconds to ensure it hasn't been cancelled before sending the request. This is called a concurrency method. Using setTimeout() will wait a certain amount of time before running any code inside of it. It is also very good to ensure users do not spam requests to your end point and wait for the newest and most recent request and return that back (if you decide to wrap your whole request in a timeout):

return axios.get('your-end-point').then(response => setTimeout(response, 1000))); 

Note: 1000 here is 1000 m/s. You can change this value to be longer or shorter depending on how long you wish to wait for.

See more about setTimeout and concurrency here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

JoshuaRDBrown
  • 343
  • 5
  • 12
  • Absolutely nothing to do with the question. – panthro Jul 08 '20 at 10:18
  • Maybe try providing more context to your question. I assume that's why you have no other answers and I was just going out on a limb. Have a look at this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield Does this answer your question? If so I will create a new answer explaining how to implement. Just a tip for future, code samples are really useful to fully visualize your issue – JoshuaRDBrown Jul 08 '20 at 18:42