0

The idea: Call async customPrompt() wait, return on button click true or false.

Currently I can display the prompt as it should be but I am stuck at the event listeners as the function only return unresolved promise

async function customPrompt() {

  prompt.classList.add('show);

  prompt.querySelector('.btnTrue').addEventListener('click', () => {
    return true;
  })

  prompt.querySelector('.btnFalse').addEventListener('click', () => {
    return false;
  })
}

How can I resolve the promise as soon as one of the buttons is clicked?

PS: I am pretty new to async/await but could not find any article online about something like this

Any help is appreciated ;)

Dorbn
  • 277
  • 4
  • 11
  • Promises shouldn't be used for things that can resolve multiple times, you should use events or callbacks instead. – Andy Ray Jun 25 '21 at 17:11
  • I assume the real code will also remove the dialog box when a button is clicked. – CherryDT Jun 25 '21 at 17:27
  • Yes, this was just a simplified example but the solution from @ponury-kostek worked and helped be solve everything – Dorbn Jun 26 '21 at 18:49

1 Answers1

2

Create Promise inside your customPrompt function and resolve it when button is click

function customPrompt() {
  return new Promise((resolve) => {
      prompt.classList.add('show');

        prompt.querySelector('.btnTrue').addEventListener('click', () => {
          prompt.classList.remove('show');
          resolve(true);
        })

        prompt.querySelector('.btnFalse').addEventListener('click', () => {
          prompt.classList.remove('show');
          resolve(false);
        })
      })
  }
}
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
  • 1
    @ddl Careful, since it seems the same HTML element is reused for successive prompts, the event listeners will get attached again and again, not only leaking memory but also attempting to resolve or reject an already resolved/rejected promise from earlier. I'd suggest storing the event listener functions in variables and removing the listeners upon hiding the prompt. (...or just universally removing all click listeners instead) – CherryDT Jun 25 '21 at 17:29
  • You should pass `{once: true}` as the third argument to `addEventListener`. @ddl I added an answer to the [linked duplicate](https://stackoverflow.com/a/68135685/633183). – Mulan Jun 25 '21 at 18:34
  • @Thank you: No this won't be sufficient because there are two listeners added but only one will be fired for every time the code is run, so the other one will stay. – CherryDT Jun 26 '21 at 04:42