JavaScript Notes

Sequential Asynchronous Functions


I recently had a situation at work where I needed to programmatically manipulate a UI on a page. Said UI would mutate based on inputs, so I needed to make sure I didn't do things all at once, or I would end up trying to reference elements that didn't exist yet. In other words, I needed to meet the following conditions:

  • Operations should be sequential, i.e. operation A needed to be completed before operation B was performed
  • Operations needed to poll until their required conditions were met (i.e. whether the element they were manipulating was available yet)
  • Operations should be asynchronous (to avoid locking the browser)

There are likely a few ways to achieve this, and I'm still getting the hang of the newer JS stuff like async/await and promises, but this one worked well for me. You could probably just nest intervals, but I wanted something a bit more elegant.

Because we have full control of the UI below, this example is pretty pointless since we could just add the changes we want in the event listeners, but hopefully you can see how it would be useful if you weren't in direct control of the page's UI.

Files: 1 2.15 KiB
async-sequential-functions.js 2.15 KiB