Read more

Destructors for async Unpoly compilers

Arne Hartherz
December 06, 2022Software engineer at makandra GmbH

Usually, Unpoly compiler destructors Show archive.org snapshot are returned from the compiler function.
However, when using async compiler functions, you can not register destructors via return.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

This will not work:

up.compiler('my-example', async (element) => {
  await something
  
  return function onDestroy() {
    // ...
  }
})

Instead, use up.destructor Show archive.org snapshot :

up.compiler('my-example', async (element) => {
  await something
  
  up.destructor(element, function onDestroy() {
    // ...
  })
})

However, note that your element might be removed from the DOM while your async function is waiting. Then, up.destructor would register the destructor function on the detached element, but Unpoly never calls that destructor and your application effectively leaks memory.
In almost all cases you can avoid that by simply checking if your element is still attached to the DOM Show archive.org snapshot when your await statement passes.

up.compiler('my-example', async (element) => {
  await something
  if (!element.isConnected) return
  
  up.destructor(element, function onDestroy() {
    // ...
  })
})
Posted by Arne Hartherz to makandra dev (2022-12-06 11:51)