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'); }); 

}

    1 answer 1

    You can write this item with promises like this:

     _openMenu(target) { new Promise((resolve) => { this._closeMenu(); target.classList.add('isActive'); target.nextElementSibling.classList.add('isOpened'); setTimeout(resolve, 0); }) .then(() => { document.addEventListener('click', this._closeMenu); }); } 

    or like this:

     _openMenu(target) { this._closeMenu(); target.classList.add('isActive'); target.nextElementSibling.classList.add('isOpened'); new Promise((resolve) => setTimeout(resolve, 0)) .then(() => document.addEventListener('click', this._closeMenu)); } 

    But I would not call any of these options correct. Because the promises in this task are not needed.

    The scope of application is the return of values ​​from a function. For example, a function that displays a modal dialog could return a promise containing the value entered by the user in this dialog.