Search code examples
javascriptrace-conditiones6-promise

JavaScript ES6 - Possible race condition between promise resolution and event?


Is it possible to have user code executed between a promise resolution and a promise await return?

function a () {
  return new Promise(resolve => {
    setTimeout(() => {
      // Between here...
      resolve()
    }, 1000))
  }
}

async function b () {
  await a()
  // ...and here ?
}

Does the specification enforces that Promise callbacks are called immediatly? I wonder if an event could be handled by the virtual machine between the 2 points, possibly causing side-effects.


Solution

  • No, it doesn't enforce immediate calling. The spec runs through a number of steps upon resolving a promise, one of which is:

    1. Perform EnqueueJob ("PromiseJobs", PromiseResolveThenableJob, «‍promise, resolution, thenAction»)

    Note that depending on the state of the promise, different routes can be taken. However, they all end at EnqueueJob, which says:

    1. Add pending at the back of the Job Queue named by queueName.

    So any further executions are deferred to the end of the job queue.