Member-only story
Making NodeJS Functions Sleep
Here are my two cats Chestnut and Rey. They’re showing what a well rested NodeJS function looks like.
When learning JavaScript for the first time, one of the biggest challenges is understanding the event loop. Unlike many other languages, JavaScript operates inside a hosted environment which determines how the code is actually ran. This means that things like scope and order can make or break JavaScript programs. It makes it harder when you want to streamline processing to force control on things like threads or API calls.
One common approach to handling things like this is using async await
. Which forces things that are async (like promises) to complete before getting a payload and making calls. I actually cover a basic walkthrough of this in my post Optimizing Angular with Async Await.
Recently, I was working on an NodeJS API that calls a set of endpoints to provide a weather forecast. I’m using some of the NOAA Endpoints that you can see here.
The issue I had was that one of the API calls would intermittently fail. What I noticed in testing was that if it failed, but I waited a few seconds and tried again, it worked. This was pretty frustrating because it would happen at different points in the day. My assumption was this was based on load etc. on the NOAA APIs. Regardless, I needed to build in some mechanism to…