【问题标题】:Is possible to block the execution until all previous JavaScript listeners completes?是否可以阻止执行,直到所有先前的 JavaScript 侦听器完成?
【发布时间】:2022-06-28 23:28:11
【问题描述】:

我对 JavaScript 很陌生,我在 SO 中搜索了很多,但我还没有找到任何合适的解决方案,不涉及链接。我有两个事件监听器,按此顺序注册。

第一个侦听器 (module_a.js) 更改表单值:

// First listener: handle submit and change recaptcha value
form.addEventListener('submit', async refreshRecaptcha() {
  const { target: form } = e;
  const recaptchaField = form.querySelector('[name="catpcha"]');

  // Simulate long running task
  await new Promise(resolve => setTimeout(resolve, 5000));

  recaptchaField.value = token;
});

第二个监听器(module_b.js)实际提交表单:

// Second listener: POST data to server, with the recaptchaField changed
form.addEventListener('submit', async postData(e) {
  e.preventDefault();

  // Post data
  await fetch(url, { method: 'POST', body: formData })
});

第二个监听器应该“等待”直到第一个监听器完成。或任何其他异步侦听器完成。 我不能将两者“链接”在一起,因为它们位于不同的模块中。

可能还是不可能?

【问题讨论】:

  • X/Y 问题。为什么所有这些异步和等待?将 fetch 移到 resolve 中
  • 我不能将两者“链接”在一起,因为它们位于不同的模块中。每个模块只做一件事

标签: javascript


【解决方案1】:

您可以使用 Promises 实现此目的。

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

myPromise
  .then(handleResolvedA, handleRejectedA)
  .then(handleResolvedB, handleRejectedB)
  .then(handleResolvedC, handleRejectedC);

【讨论】:

  • 无法链接,不同的文件/模块
猜你喜欢
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
相关资源
最近更新 更多