Chaining Fetches
I would like to preface this blog by saying, I don’t think this is the most efficient way to solve this problem but I thought it was interesting.
During my most recent project, I had 7 post requests I needed to make from one handleClick(). When I ran them all asynchronously, sometimes a few posts would work, but I would mostly be catching 500 errors. I figured it was because they were running asynchronously and one fetch would start before the previous one finished and the system would metaphorically trip over itself. So I googled how to delay a fetch request and all I got was about timeouts. I didn’t want this to rely on time, I wanted my fetch requests to line up like school children and wait their turn. So my solution was to tediously chain them together using .then().
Normally a fetch would be ended with a:
.then(r => r.json())
.then(data => someFunction(data))
Well I decided to take my 7 post requests and put them in their own functions and use the .then() to chain them together so that the next one only starts fetching after the previous one ends. I will attach an example from my code below:
This chaining perfectly fixed my issues and has prevented the code from tripping all over itself. I hope this has been helpful to anyone struggling with async fetches like I have.