Tengo que usar este código js para agregar una matriz tomando valores de los botones en los que se ha hecho clic. Entonces, los almacené en una matriz para pasarlos a la función que se agregará a mi HTML principal. El problema al que me enfrento es que se agrega a la matriz con cada botón en el que hice clic, pero no dará tiempo para que se ejecute cada elemento. Muestra directamente el efecto del último elemento.
// We create a Promise and return it new Promise((resolve, reject) => { const animationName = `${animation}`; const node = document.querySelector(element); node.classList.add(`${prefix}animated`, animationName); // When the animation ends, we clean the classes and resolve the Promise function handleAnimationEnd(event) { event.stopPropagation(); node.classList.remove(`${prefix}animated`, animationName); resolve("Animation ended"); } node.addEventListener("animationend", handleAnimationEnd, { once: true }); }); var arrayOfButtonId = []; var counter = 1; $(".buttons-container").click(function (e) { var clickedItemId = e.target.id; // var clickedItemValue = e.target.value; arrayOfButtonId.push(clickedItemId); arrayOfButtonId.forEach((index) => { console.log(index); animateCSS(".sample-display", index).then(() => { alert(" animation created successfully!"); }); }); });Este es el código que traté de implementar.
Pregunta súper clásica, no puede esperar que un mecanismo asíncrono como Promise (incluso con await , y mucho menos con .then() ) funcione dentro de un método Array sincrónico (forEach, map, filter, etc.) como se explica aquí .
Necesitas for y async/await :
$(".buttons-container").click( async function (e) { var clickedItemId = e.target.id; arrayOfButtonId.push(clickedItemId); for( let index in arrayOfButtonId){ console.log(index); await animateCSS(".sample-display", index); console.log("animation created successfully!"); } }); Además, suelte la alert() porque está bloqueando su interfaz de usuario y anula el propósito del asincronismo. Utilice console.log en su lugar.