JavaScript ES6 - Possible race condition between promise and event?

Is it possible for custom code to be executed between resolving a promise and the promise is pending return?

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

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

Does the specification indicate that Promise callbacks are called immediately? I wonder if the event can be processed by the virtual machine between two points, which can cause side effects.

+4
source share
2 answers

No, it does not provide an immediate call. The spectrum goes through several steps in resolving a promise, one of which is:

  1. EnqueueJob ( "PromiseJobs", PromiseResolveThenableJob, ", , thenAction" )

, . , EnqueueJob, :

  1. queueName.

, .

+4

. b()

function b () {
  return a().then(() => {
    // Do something
  });
}

, then, eventloop , a. , , Promise ( , eventloop). (, ) , , .

+1

Source: https://habr.com/ru/post/1682201/


All Articles