0

Functions in pure JavaScript are synchronous by default. Is there a way to convert synchronous functions to become asynchronous.

Note: I don't want to use setTimeout function (Or setImmediate In Node.js). Just ECMAScript specs. Tried to add async keyword but the result is the same synchronous behavior.

The Example below illustrates the default behavior.

Code:

console.log("start");

function countTo100Mill() {
  for(i=0; i <= 100000000; i++) {
    if(i === 100000000) {
       console.log("count to 100mill complete");
       }
  }
}

function countTo100() {
  for(i=0; i <= 100; i++) {
    if(i === 100) {
       console.log("count to 100 complete");
       }
  }
}

countTo100Mill();

countTo100();

console.log("end");

Default Behaviour:

The function countTo100Mill will run before countTo100 no matter the delay.

What I Want To Achieve:

I want a way to convert the functions defined in the code above to run asynchronously so that countTo100 will complete followed by countTo100Mill.

claOnline
  • 1,005
  • 3
  • 10
  • 18
  • 1
    You need to use `setTimeout`/`setInterval`/`setImmediate` - there is literally no other way – slebetman Aug 24 '19 at 11:09
  • 1
    @slebetman Disagree, this is achievable (but really weird) with `await` – CertainPerformance Aug 24 '19 at 11:13
  • 1
    Promises do provide some EcmaScript-native asynchronous functions to use, but it would work just the same as using `setTimeout`/`setImmediate`. – Bergi Aug 24 '19 at 11:13
  • 1
    When you added the `async` keyword, did you also `await` anything? Only that makes the rest of the function body run later. – Bergi Aug 24 '19 at 11:15
  • @Bergi no I did not add the await keyword. Is it not supposed to work without the await keyword – claOnline Aug 24 '19 at 11:16
  • 1
    @claOnline `await` does nothing to your code. I was in the middle of writing an answer before this was marked as duplicate. If you really want to run your code in a different thread (which is what you imply you want, not simply make it asynchronous - run in unpredictable order) then you can use something like `worker_threads` - https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads or some other threading library like `webworker-threads` from npm – slebetman Aug 24 '19 at 11:20
  • 1
    @claOnline No, an `async function` starts running its code immediately when called. Only `await`ing something brings in asynchrony. But I would suggest to drop the `async`/`await` syntactic sugar for this exercise and use promises with their `then` method explicitly. – Bergi Aug 24 '19 at 11:20

0 Answers0