shmth
shmth

Reputation: 498

Can promises execute out of order in Javascript?

Let's say I have some code like this:

const someAsyncFunc = async (num) => {
  console.log(num);
}

someAsyncFunc(123);
someAsyncFunc(234);

Is it theoretically possible that 234 will be printed first? In general, if I invoke one async function before another, is it guaranteed that the first function will begin executing before the second one begins executing? Do I have to assume that any promise may be delayed indefinitely before it starts executing, or is there some guarantee on when it starts executing?

Upvotes: 0

Views: 34

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138467

Yes, it is guaranteed. Actually async functions execute synchronously till the first await. It gets more interesting if we add an await:

  const someAsyncFunc = async (num) => {
   console.log(`before ${num}`);
   await Promise.resolve();
   console.log(`after ${num}`);
  };

  someAsyncFunc(1);
  someAsyncFunc(2);

Now that will produce "before 1, before 2, after 1, after2". That order will never change, because the task to continue execution of the function gets enqueued into a task queue (synchronously, as the Promise resolves immeadiately) and therefore the order is guaranteed too.

Now if you await two Promises that will resolve at different times in the future, then the order might differ.

Upvotes: 1

Related Questions