1
document.querySelector('#library').addEventListener('click', function(event) {

  new Promise((resolve => {
    setTimeout(() => {
      resolve('set time out');
    }, 2000)
  })).then(console.log)

  // if response
  console.log('stop propagation')
  event.stopPropagation();
  event.preventDefault();
  // else
}, true)

I need to click an element. This will make a request and based on response (will return true or false), this will enable or disabled the click. But console.log('stop propagation') is executed before .then(console.log).

mplungjan
  • 169,008
  • 28
  • 173
  • 236
S. Wasta
  • 599
  • 9
  • 35
  • You may need to define the Callback-Function as async and use async/await. See https://gist.github.com/nickytonline/069fc006d1946279a31fed10a61d08c5 – B Polit May 27 '21 at 07:07
  • 1
    You cannot really disable click until a promise resolves. What you can do is disable the click and then after the promise resolves do an action (or not do an action) based on the promise. – VLAZ May 27 '21 at 07:08

1 Answers1

5

You can't wait for an asynchronous operation to complete if you want to stop propagation and prevent the default. In this case your promise wont halt the code at all, but even if you implement a "sleep" function properly (using async/await), it will still need to wait for the promise to resolve, before it is able to know whether it should continue or not. JavaScript doesn't wait for that answer and will execute the default action and propagate further before you decide to stop that.

If you want to postpone this action, you'll have to first prevent the default and the propagation, then wait for the promise to resolve and then if the answer is to your satisfaction, continue with whatever it should be doing.

document.querySelector('#library').addEventListener('click', async function(event) {
  console.log('stop propagation')
  event.stopPropagation();
  event.preventDefault();

  const returnValue = await new Promise((resolve => {
    setTimeout(() => {
      resolve('set time out');
    }, 2000)
  })).then(resolvedValue => {
    console.log(resolvedValue);
    return resolvedValue;
  })

  if (returnValue === 'set time out') {
    location.href = event.target.href;
  }
}, true)
<a id="library" href="http://www.google.com/">Click</a>
Ivar
  • 6,138
  • 12
  • 49
  • 61