ES5 has been around for a few years now and it’s safe to say that most developers are using the new features in all of their JavaScript applications — assured of the wide support among modern web browsers. Some of the useful functional-programming-inspired features of ES5 included the array methods forEach/map/reduce; these features are merely syntactic sugar, but they are nice to use none-the-less.

Here we are a few years later, and now the async/await keywords are all the rage. I won’t go into too much detail on how async/await works in this blog post, but essentially an async function is just a wrapper around the Promise API.

If you are just getting started with async/await you might be keen to run a bunch of asynchronous functions in series (one after the other). Promise.all is a great method if you do not care about the execution order of the asynchronous functions and can just run them in parallel, getting a final resolved promise once everything has been completed. But what if you want to run them in series? Let’s imagine you had an array upon which you wanted to run async functions in series, you might try something like this:

If you run this code, you’ll see a single brief pause of 500ms before every element of the array calls console.log, appearing all at one. The problem is that, for legacy support reasons, Array.prototype.forEach does not respect async functions and it will treat it just as a normal function. In order for the forEach loop to work as series, you would have to create a new function and assign Array.prototype.forEach to that function.

Of course, in professional programming circles, extending the prototype of a native JS object — such as Array — is generally considered bad practice for the primary reasons of interoperability and code reuse. To go off on a slight tangent, the reason ‘forEach’ is called ‘forEach’ and not simply ‘each’ is because back in the day some popular JS libraries were embracing the dark art of extending the Array.prototype with a custom ‘each’ method. In order to standardise an each method, whilst at the same time not break a good number of websites, it was decided to call the method ‘forEach’, and let those rascal websites do their worst with their custom ‘each’ methods.

But seeing as this is just a demonstration, it can be fun and liberating to disobey best practices. So this is how simple it would be for you to add your own ‘asyncForEach’ method to the Array.prototype, and thus provide an easy way to call async functions in series:

Notice how the definition of ‘asyncForEach’ is itself an async function which calls ‘await’ within the for loop to pause execution of the loop until the promise of that function ‘fn’ is resolved. When you run this code, you’ll see each of the letters from the array printed to console one after the other — 500ms in between each console.log.