I'm quite new to JavaScript, I've searched a lot in SO but I have not find any suitable solution yet, not involving chaining. I have two event listeners, registered in this order.
First listener (module_a.js) changes a form value:
// 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;
});
Second listener (module_b.js) actually submit the form:
// 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 })
});
Second listener should "wait" until the first completes. Or any other async listeners complete. I cannot "chain" together the two because they are in different modules.
Possible or impossible?
You can achieve this using Promises.
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }); myPromise .then(handleResolvedA, handleRejectedA) .then(handleResolvedB, handleRejectedB) .then(handleResolvedC, handleRejectedC);