I am trying to learn promises from the new ES6, while the essence and purpose are hard to understand. I tried to find a simple task for myself in which I can apply them.
There is a regular menu that opens on click. it has a method for discovery
_openMenu(target) { this._closeMenu(); target.classList.add('isActive'); target.nextElementSibling.classList.add('isOpened'); setTimeout(()=> document.addEventListener('click', this._closeMenu), 0); } The last line is not a big crutch. The menu should be closed when you click on any other place in the document, so the handler is hung up. So because of the handler, the menu immediately opens and closes. hangs timeout solving this problem.
I tried to rewrite it with promis, but the result does not help, the menu also collapses, how to write promis for asynchronous execution correctly?
_openMenu(target) { Promise.resolve() .then(() => { this._closeMenu(); target.classList.add('isActive'); target.nextElementSibling.classList.add('isOpened'); console.log('step 1'); return Promise.resolve(); }) .then(() => { document.addEventListener('click', this._closeMenu); console.log('step 2'); }); }