79171316

Date: 2024-11-08 19:27:39
Score: 3
Natty:
Report link

I'm risking some reputation here... But I'll gamble a little...

For short...

"Can a race condition occur after the user clicks the modal OK, between the callback (a) that sets the boolean, and the Promise callback (b) that tests it?"

Yes! It can. How to do it? Well... that's another question.

But, I want to remind that a race is something asynchronous that happens between promises. It's like "give me the result of the promise (in a set of them) that fulfills first".

Your example/explanation/details only points out one Promise. So where's the need for a race?

I'm guessing you have a submit event handler that shows the modal and sets the promise... Then you want the promise to await for the ok button effect on the modal? If so you can try something like this:

const form = document.querySelector('#myForm');
const modal = document.querySelector('#myModal');
const modalButton = modal.querySelector('#myOk');
const variable = document.querySelector('#myVar');

form.addEventListener('submit', submitEventListener);
modalButton.addEventListener('click', okEventListener);

function okEventListener ( event )
{
  variable.value =
  (
    (variable.value == 'true')
    ? 'false'
    : 'true'
  );
  
  modal.open = false;
  
  console.log('OK sets a new variable value:', variable.value);
  
  event.target.resolver(variable.value);
}

async function submitEventListener ( event )
{
  event.preventDefault();
  
  // Do ajax stuff here...
  
  let newPromise = new Promise
  (
    async ( resolve, reject ) =>
    {
      modalButton.resolver = value => resolve(value);
    }
  );
  
  modal.open = true;
  
  console.clear();
  console.log('Current variable value:', variable.value);
  
  // You can make any race here, including newPromise.
  console.log('Suppose that a race is running starting now.');
  
  // This will await for the user to click ok on the modal.
  await newPromise; // or await your race...
  
  // Then print something to the console...
  console.log("Awaited for the variable changed value:", variable.value);
}
dialog
{
  background-color: lightgray;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  margin: 0;
  padding: 0;
  border: 0 solid black;
}
<dialog id="myModal">
  <button id="myOk">OK</button>
</dialog>
<form method="dialog" action="about:blank" id="myForm">
  <label for="myVar">
    VARIABLE:
    <input type="text" id="myVar" name="myVar" value="true" disabled="disabled" />
  </label>
  <button id="openModal" type="submit">Open Modal</button>
</form>

PS.: As no code was exposed in the question, I made one out of my imagination as an example.

Reasons:
  • Blacklisted phrase (1): another question
  • RegEx Blacklisted phrase (1.5): reputation
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: KLASANGUI