Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Order of resolution for multiple awaits on one promise without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
If multiple tasks are waiting on a single promise, is there a guaranteed/specified by a standard order in which those tasks will begin executing once the promise is resolved? For example, consider the following
var promise = null; function setPromiseIfNeeded() { if (!promise) { promise = new Promise(resolve => setTimeout(resolve, 100)); } } client.on('event1', event => { setPromiseIfNeeded(); await promise; console.log('event 1 done awaiting'); } client.on('event2', event => { setPromiseIfNeeded(); await promise; console.log('event 2 done awaiting'); }
If event1
occurs before event2
, is it guaranteed that the handler for event1
will awake from its promise before the handler for event2
?
If the behavior is implementation dependent, I’m particularly curious about the behavior for node.js v12 and above.
Answer
Yes, this is guaranteed. Promise handlers (then
callbacks) are run in the same order in which they were installed on the promise (.then()
call). This translates into the same for await
syntax.
We are here to answer your question about Order of resolution for multiple awaits on one promise - If you find the proper solution, please don't forgot to share this with your team members.