0

Can you suggest why callbacks in Angular2 promise implementation are executed via asap function. Here is a link to implementation.

So in my browser callbacks are executed in BrowserMutationObserver thread. Why did they implement additional queue for callbacks instead of executing them in thread that resolves promise or if promise already resolved execute callback in the same thread?

Nithin Kumar Biliya
  • 2,763
  • 3
  • 34
  • 54
user877315
  • 31
  • 4
  • Because [it's requrired](https://promisesaplus.com/), and guaranteed asynchrony is not a bad thing. – Bergi Jan 19 '16 at 23:38
  • Thanks for link to specification. I see this requirement "In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack." in specification. But I still have some questions: 1) What is a profit of executing onFulfilled and onRejected methods asynchronously for already resolved Promises. 2) Do you see any reason why they implemented asynchronous execution via MutationObserver not Web Worker, I thought Web Worker was designed for asynchronous tasks. – user877315 Jan 20 '16 at 10:36
  • As I mentioned, the profit is guaranteed asynchrony. You can expect consistent behaviour, regardless when the promise resolves (has resolved). See also https://stackoverflow.com/questions/29963129/is-javascript-promise-callback-executed-asynchronosuly – Bergi Jan 20 '16 at 16:29
  • Web Workers are for background processing. While their communication with the "main thread" is asynchronous, they are not suitable for promises as the worker environment doesn't have access to the main scope. The mutation observer thing is just an elaborate and more efficient way to write `setTimeout(…, 0)`. – Bergi Jan 20 '16 at 16:33

0 Answers0