ProTip™: Async/Await IIFEs for Background Tasks

Published

I was recently looking over a code review in the wild and was particularly fascinated when code resembling the following was proposed:

// Inside of a parent `async` function

(async () => {
  await myLibrary.someCleanUpFunction();
  await myOtherLibrary.anotherOne();
})().catch(console.error);

It’s a pattern that I haven’t seen much of before: doing the async IIFE pattern inside the body of an async function. The logic being, in this case, wanting to run some code in the background” but still handle errors vs await for those tasks inside the function body.

The reviewer was not a fan of this syntax, so the resulting code compromise was refactoring to the following:

async function runInBackground(func) {
  try {
    await func();
  } catch(e) {
    console.error(`Background task failed: ${e}`);
  }
}

runInBackground(async () => {
  await myLibrary.someCleanUpFunction();
  await myOtherLibrary.anotherOne();
});

I’m definitely going to keep this proverbial toolbox of knowledge, just like how I learned from Todd Gardner that there’s a use case for doing a setTimeout(() => {}, 0) inside of a requestAnimationFrame which completely blew my mind. Specifically, this done for wanting to execute some code immediately after a repaint.


I love hearing from readers so please feel free to reach out.

Reply via emailSubscribe via RSS or email

Last modified  #protip   #programming   #web   #js 


← Newer post  •  Older post →