-2

Codepen link: https://codepen.io/AnirudhMS/pen/poRmjao?

Code:

console.log('Started script execution.');
(async () => {
  let promiseWrapper = async () => {
    setTimeout(() => {
      console.log("Inside async script.");
      Promise.resolve();
    }, 0);
  };
  await promiseWrapper();
})();
console.log('Finished script execution.');

Output:

Started script execution.
Finished script execution.
Inside async script.

Issue: As can be seen from the above output, in top-level code, the browser does not wait for async operations to finish. Now this also means that an event like dom-ready will be fired after the synchronous code has finished executing. The problem is not with the dom-ready event exactly but is there a way to ensure that the output is as follows:

Started script execution.
Inside async script.
Finished script execution.

Edit: Note: The solution needs to work if I replace the setTimeout with an await Promise call!!!

Edit 2: The solution needs to be such that the dom-ready event or the DOMContentLoaded event is fired after the execution of the async script. Is that possible?

Black Wind
  • 313
  • 1
  • 8
  • 1
    Why the downvotes? –  Apr 28 '21 at 22:00
  • @Dominik would the solution you pointed to work in case I wanted to execute a Promise in place of the `setTimeout` ?? – Black Wind Apr 28 '21 at 22:05
  • This seems like an XY problem. You have some issue and try to fix it by hacking the system. So what are you trying to do in the first place, and what doesn't work there? – Thomas Apr 28 '21 at 22:44

1 Answers1

0

First, you shoud return Promise, not only use Promise.resolve inside timeout callback, second, use promise-like variant in top scope:

console.log('Started script execution.');
(async () => {
  let promiseWrapper = () => new Promise((res, rej) => {
    setTimeout(() => {
      console.log("Inside async script.");
      res();
    }, 0);
  });
  await promiseWrapper();
})().then(() => {
  console.log('Finished script execution.');
})
A Ralkov
  • 1,046
  • 10
  • 19