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!
The main point of something like this:
is just to call
someNextMethod()after the current chain of execution finishes. In a browser, it is similar to this:though the
Promise.resolve()method will prioritize it sooner thansetTimeout()if other things are waiting in the event queue.So, in your particular example, the point of these two statements:
is to call
someNextMethod()afterthis.somethingThatTakesAWhile()returns and after theMutationObservercallback has returned, allowing any other observers to also be notified beforesomeNextMethod()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.