WeweroWawora Wooo
WeweroWawora Wooo

Reputation: 21

javascript function returns undefined instead of array values?

let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  let btnsPair = [chices1[0], chices1[1]];
  btnsPair.forEach((choice) => {
    choice.addEventListener("click", (c1) => {
      let mychoice = c1.target.textContent;
      return mychoice;
    })
  })
}
console.log(choosenOrder(btns));

//return undefined

I will be simple and direct...

I want to return the text value of the button i press using the listener function inside addEventListener. However this is not working as expected, and what ever i try it either returns undefined or not work at all, is it even possible to return a value from an event listener?

If it is not, what kinda of alternatives do I have?

Thanks in advance!

Upvotes: 2

Views: 456

Answers (1)

blex
blex

Reputation: 25634

The return statement is inside the event handler, and cannot be taken into account by the wrapping function (when the handler is executed - asynchronously, the wrapping function call has already ended and returned). An alternative could be to use Promises. In the outer function, return the Promise, and inside the event listener, resolve that Promise with the value:

let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  return new Promise(resolve => {
    let btnsPair = [chices1[0], chices1[1]];
    btnsPair.forEach((choice) => {
      choice.addEventListener("click", (c1) => {
        let mychoice = c1.target.textContent;
        resolve(mychoice);
      });
    });
  });
}

choosenOrder(btns).then(console.log);
<button>Choice A</button>
<button>Choice B</button>

Upvotes: 1

Related Questions