0

I have written something like;

self.handleAction = async function (event) {
    $("#someDivID").show();

    await __method1();
    //log something
    await __method2();

    $("#someDivID").hide();
}

The thing is, I know the __method1() and __method2() will take time to execute and hence I'm using the async-await approach here.

The JQuery show and hide methods are supposed to show a certain div while the processing is happening (kind of like a loading gif.) I'm using the same code in other flows in the code and it works fine.

Observation;

  • The code does nothing seemingly asynchronously.
  • The JQuery approach to show and hide a certain element at the start and end of the function is never seen.

Questions;

  • Is the expectation to have the __method1 and __method2 run asynchronously in such a code structure incorrect? What am I missing?
  • Why would the show() and hide() methods not be working as expected here?

P.S - In other areas where similar async-await and the show-hide approach is being used, I have fetch() calls and promises in the picture. This method event however is pure computation and no fetch API's are involved.

Shivam Puri
  • 1,578
  • 12
  • 25
  • 7
    "*The code does nothing seemingly asynchronously.*" then most likely `__method1()` and `__method2()` are not asynchronous. Slapping an async and await in the code doesn't make the code multithreaded or parallel or anything of the like. If the code is blocking, it's still blocking. – VLAZ Jun 07 '22 at 10:29
  • if you're using any loops (for, while, do...while) inside `__method1` or `__method2` then they will behave synchronously regardless of async-await – acetheninja Jun 07 '22 at 10:30
  • 5
    And the show/hide will be without effect, because the paint cycle will only occur after the microtasks (executing your methods) have completed. – trincot Jun 07 '22 at 10:31
  • So basically: What are `_method1` and `_method2`? Without knowing that, we can't help you further than the comments above do. – T.J. Crowder Jun 07 '22 at 10:32
  • Some ideas: use `setTimeout` and break up your calculation in small chunks. Or use Web workers for executing the methods (and hope your DOM still doesn't block). – trincot Jun 07 '22 at 10:35
  • As @trincot has stated, simply wrapping your `__method1()` `__method2()` and `$().hide()` in a `settimeout(_, 1)` will allow the dom to at least `show()` the initial div. It will still block the UI while your methods are executing, but the div will be displayed. – Pellay Jun 07 '22 at 10:39
  • Thanks for the comments....The __method1 and 2 are not async. They are just normal functions being called to read some huge maps and perform some actions there. Are we saying that making the ```method1``` and ```method2``` as ```async``` would help? – Shivam Puri Jun 07 '22 at 11:17
  • No, we are not saying that. – trincot Jun 07 '22 at 11:20

0 Answers0