1

I have added one button in UI. onclick of this button I am calling a function which is returning promise. This piece of code supposed to not block the UI but this is blocking the UI.

    <button onclick="block()">Click Me</button>

    const blockUI = () => {
        return Promise.resolve().then(_ =>{
           console.log('loop start');
           let i=0;
           while(i<10000000000) {
              i++;
           }
        return 'loop end'
    });
   }

 const block = ()=> {blockUI().then(d => {
    console.log(d);
 })}

How can I make this async?

Rahul
  • 5,594
  • 7
  • 38
  • 92
  • Hm, the problem is that intensive CPU will bock the event loop hence the UI block. – EugenSunic May 06 '20 at 09:20
  • @EugenSunic that means I can't make it asyncrhonous? – Rahul May 06 '20 at 09:22
  • Yes I believe your UI will remain blocked under intensive CPU work. Let's see if an expert can give a better answer if I may be wrong... – EugenSunic May 06 '20 at 09:23
  • 1
    Your code is actually synchronous. Check [this post](https://stackoverflow.com/questions/54478255/why-is-my-infinite-loop-blocking-when-it-is-in-an-async-function). – Oleksandr Demian May 06 '20 at 09:23
  • 1
    @EugenSunic this thing making my understanding on Promises incorrect. This was supposed to be run async. If it is blocking the UI then there is no use of promises. It just behaving like normal synchronous code. – Rahul May 06 '20 at 09:25
  • @Dalvik Yes. Promises do not *make* anything asynchronous themselves, they're only a tool that makes working with asynchronous things easier. And they definitely do not make CPU-intensive code run in parallel or something, that's what workers are meant for. – Bergi May 06 '20 at 09:50
  • async != concurrent – xehpuk May 06 '20 at 13:35

0 Answers0