Gotchas with JavaScript Promises and Fetch

This year has definitely been one of “return to JavaScript” for me (among other things) and its really interesting to see how far it has come. Between Cloud Functions, complex client applications using React, native app development with React Native and now even using AFrame/ThreeJS for WebVR development, I have been writing a LOT of JavaScript across the stack.

JavaScript’s increased responsibilities have unfortunately brought with it a corresponding increase in complexity which trips up many a returning developer (Gina Trapani’s excellent post is a good read if you are one of This month I have spent quite a few hours dealing with JavaScript’s Fetch API and the whole Promises API. There are a couple of gotchas there that I ran into that are worth sharing. Maybe they can save you a couple of hours down the road

  1. Fetch and Promises start executing immediately. You cannot create a Promise object and store it to be executed later. If you are trying to avoid that, one option is to create a function that returns the Promise when needed.
  2. Fetch requests have no concept of a timeout. If you need a Fetch request to be aborted after a certain number of seconds, the best way I have seen is to use Promise.race along with a different function that then throws the error to reject the Promise chain.
  3. Making multiple calls with Fetch? Promise.all is a great option except that all requests / Promises start executing in parallel. If you need to execute them in sequence (like I did), you are out of luck without writing some utility code or leveraging a library. I ended up using this npm module.
  4.  Server error responses to Fetch calls are still interpreted as successes and call the success callback handler. Which means that you have to check for errors in your onSuccess which feels just wrong.

These are definitely some … debatable calls made by the guys deciding the api. If there are other gotchas you have run into, please share them here as well.