Home > Blockchain >  How does this promise without an argument work in this mutation observer?
How does this promise without an argument work in this mutation observer?

Time:02-05

I was looking at this mutation obersver in some typescript code and I can’t figure how the promise works in it, I’ve not see a promise without an argument in this style before:

  const observer = new MutationObserver((mutations: MutationRecord[]) => {
    Promise.resolve().then(someNextMethod)
    this.somethingThatTakesAWhile()
  })

  observer.observe(HTMLtarget)

When the observation is triggered the someNextMethod runs after this.somethingThatTakesAWhile() has ran. How is this possible in this instance? I don't understand how the Promise get passed any arguments and knows how to resolve in this case. Could someone explain the internal mechanics of this code please? I'm at a bit of a loss as to how it runs in that order. Thanks!

CodePudding user response:

This:

 Promise.resolve().then(someNextMethod)

Is equivalent to this:

 Promise.resolve().then(() => someNextMethod())

Working backward is equivalent to:

const myNewMethod = () => someNextMethod()
Promise.resolve().then(myNewMethod)

Defining a function inline or pointing to a function is just a syntactical difference. All of the arguments passed through then will be passed to the referenced function. But in this case, there isn't any as it's a promise with an empty return value.

In other words, the method doesn't need any parameters. In this instance it's actually just an old JS hack/trick to get the code to run at the end of the call stack.

CodePudding user response:

The main point of something like this:

 Promise.resolve().then(someNextMethod)

is just to call someNextMethod() after the current chain of execution finishes. In a browser, it is similar to this:

setTimeout(someNextMethod, 0);

though the Promise.resolve() method will prioritize it sooner than setTimeout() if other things are waiting in the event queue.


So, in your particular example, the point of these two statements:

Promise.resolve().then(someNextMethod)
this.somethingThatTakesAWhile()

is to call someNextMethod() after this.somethingThatTakesAWhile() returns and after the MutationObserver callback has returned, allowing any other observers to also be notified before someNextMethod() is called.


As to why this calls someNextMethod() later, that's because all .then() handlers run no sooner than when the current thread of execution completes (and returns control back to the event loop), even if the promise they are attached to is already resolved. That's how .then() works, per the Promise specification.


Why exactly someone would do that is context dependent and since this is all just pseudo-code, you don't offer any clues as to the real motivation here.

  • Related