0

First off, sorry for the ugly code I was just trying to figure out how promises work and I accidentally created this. It works, but I'm not sure why.

I attached an event listener to my delete button that shows the modal and creates some variables. Then my promise function references those variables. I'm trying to understand how my promise function can have references to those variables if they are block scoped to my showDeleteModal function?

Here's the code

const deleteBtn = document.querySelector('#deleteBtn');

deleteBtn.addEventListener('click', () => {
  // Not a real modal
  showDeleteModal()
})

function showDeleteModal() {
  // Create variables
  const deleteModal = document.querySelector('#modal');
  const dontDelete = document.querySelector('#dontDelete');
  const yesDelete = document.querySelector('#yesDelete');
  deleteModal.style.display = 'block';
}

const deletionPromise = new Promise((resolved, rejected) => {
  // How am I able to reference them here ?
  yesDelete.addEventListener('click', () => {
    resolved('delete the item')
  })

  dontDelete.addEventListener('click', () => {
    rejected('dont delete item')
  })

})

deletionPromise.then(data => {
  console.log(data);
}).catch(err => {
  console.log(err);
})

  • 1
    `yesDelete` is *not* the `const yesDelete` you declare in the other function. You have an element with an ID `yesDelete` and all IDs are automatically made into global variables. So, you're referencing the global variable. Same with `dontDelete`. However, if you try it with `deleteModal` you'd get a ReferenceError as there isn't an element with this ID. – VLAZ Nov 21 '20 at 17:11
  • Oh wow! Never new that. Thanks a lot! – Bryan Almaraz Nov 21 '20 at 17:14

0 Answers0