Search code examples
javascriptmemorymemory-leaks

Will a never fulfilled promise cause a memory leak?


this question is not new on SO, but I have a scenario that is not exactly the same as other questions.

Let's say I have a class Component

class Component {
  constructor() {
    this.resolvers = [];
  }

  addResolver() {
    return new Promise((resolve) => {
      this.resolvers.push(resolve);
    });
  }

  callResolvers() {
    this.resolvers.forEach((resolver) => resolver());
  }
}

Then I have this snippet of code

let components = [];

async function addComponent() {
  const component = new Component();

  components.push(component);

  await component.addResolver();

  console.log("resolver called");
}

function deleteComponents() {
  components = [];
}

function resolveComponents() {
  components.forEach((component) => component.callResolvers());
}

addComponent();
addComponent();
addComponent();

resolveComponents();

If I call resolveComponents() the resolvers are called.

My concern is if instead of resolveComponents(), I call deleteComponents(), like this:

addComponent();
addComponent();
addComponent();

deleteComponents();

Will that garbage collect the components?

They have unfulfilled promises, the resolvers for these promises are stored in the component.resolvers.

Since the previous components will be impossible to reach after the deletion, my guess is that they will be collected even though they have unfulfilled promises.

What's the answer to this?


Solution

  • You have no circular dependencies, and calling deleteComponents lets go of the only reference you have to them. So the components won't be leaked