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>