Stimulus.js wait for all controllers to initialize

13 Jul 2020

Sometimes you need to execute some code immediately after all controllers finish initialize. But stimulus does not supply an API for you to do this kind of things.

After some research I found two solutions:

initialize() {
  setTimeout(() => {
    console.log(this.getChild(this.childTarget))
  })
}

or

initialize() {
  Promise.resolve().then(() => {
    console.log(this.getChild(this.childTarget))
  })
}

For me, the empty promise solution Promise.resolve().then() is simple and easy enough for me.

You may want ask why? The answer is reltive to how JS engine execute the code.

Event loop will check whether the Call Stack is empty, it will push the callback into call stack when call stack is empty – Little Javascript

So the Promise as a kind of callback, will be execute when all function call stack is empty. When the promise being executed, all controllers(synchronize code) has been initialized.

References

Back to top