How to run async JavaScript functions in sequence or parallel
The async and await keywords are a great addition to Javascript. They make it easier to read (and write) code that runs asynchronously. That includes things like:
API calls (using fetch or a library like axios);
Timeouts (though these need a little extra work); or
Reading/writing files if you’re using NodeJS.
I’m going to assume you’re familiar with Promises and making a simple async/await call. Where it can get tricky is when we have a whole bunch of tasks in an array. You might run through the array expecting calls to run one-by-one. But instead, they run through all together and don’t wait for each individual item to resolve. Or, you might find yourself with the opposite problem. You run through your array in a loop, wanting them to run in parallel. But instead, it waits and does them one by one. And sometimes, you try something and it doesn’t work at all. The program just continues after the loop instead of waiting until the calls are all done. You end up wondering if there’s something you’re missing.