如何异步事件处理程序?等待承诺javascript

S. *_*sta 1 javascript event-handling mouseevent

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)
Run Code Online (Sandbox Code Playgroud)

我需要单击一个元素。这将发出请求并根据响应(将返回truefalse),这将启用或禁用点击。而是console.log('stop propagation')在之前执行的.then(console.log)

Iva*_*var 6

如果您想停止传播并防止出现默认情况,则不能等待异步操作完成。在这种情况下,您的承诺根本不会停止代码,但即使您正确实现“睡眠”功能(使用async/ await),它仍然需要等待承诺解决,然后才能知道是否应该继续或不。JavaScript 不会等待该答案,而是会执行默认操作并在您决定停止之前进一步传播。

如果您想推迟此操作,则必须首先阻止默认值和传播,然后等待承诺解决,然后如果答案令您满意,则继续执行应该执行的操作。

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)
Run Code Online (Sandbox Code Playgroud)
<a id="library" href="http://www.google.com/">Click</a>
Run Code Online (Sandbox Code Playgroud)