meaning of operation within executor of Promise is asynchronous

Viewed 113

In this document: MDN - Promise() constructor

there is a phrase:

  1. The operation within executor is asynchronous and provides a callback.

And here is code

console.log('before promise');
new Promise(function(resolve, reject) {
  console.log('promise');


  let j = 0;
  for (i = 0; i < 1000000000; i++) {
    j++;
  }
  resolve(1);
  console.log('promise end');

}).then(function() {
  console.log('then');
});

console.log('not promise but after');

It displays in console

  • before promise
  • promise
  • promise end
  • not promise but after
  • then

I thought once operation within executor is asynchronous, then Javascript should not wait for finish of code within executor , and "not promise but after" should be displayed right after "before promise". But it seems i do not understand meaning of this phrase. Can please someone explain what does it mean?

2 Answers

Let's look at the the context around what you quoted:

And so, given all the above, here’s a summary of the typical flow:

  1. The operation within executor is asynchronous and provides a callback.

MDN is describing a typical flow.

The operation in the executor that you passed to the Promise constructor is not asynchronous (which making using a Promise pointless).

The promise executor is run synchronously – in the case of an async function, up until the first await within it.

If you wanted something like your use case, i.e. doing lots of synchronous computation but occasionally yielding to let other things happen, you could make your function async and have it wait (setTimeout here; could be the non-standard setImmediate) every now and then.

You can also do this without using async, but it's a bit of a pain to get right.

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function doThings() {
  console.log("promise");
  let j = 0;
  for (i = 0; i < 1000000000; i++) {
    j++;
    if (i && i % 100000 == 0) await delay(0); // magic yield
  }
  console.log("promise end");
  return j;
}

console.log("before promise");
doThings().then(function () {
  console.log("then");
});
console.log("not promise but after");
Related