-1

I need to implement the following algorithm.

  1. Set expectations for the appearance of the class '.cdn_download_item'
  2. Click on the link (only after that the class '.cdn_download_item' appears)
  3. Triggering DOM Inserted=>Make a list of links and display them

Now I have a Promise {} inside which there is a list that I need, in principle everything worked, but why is the state of the promise pending, and not fulfilled? And how to make it fulfilled?

(async function() {
  var returnArray = new Array();

  function wait(selector) {
    return new Promise((resolve) => {
      const listener = () => {
        const node = document.querySelector(selector);
        if (node) {
          document.removeEventListener('DOMNodeInserted', listener);
          resolve(node);
        }
      };
      document.addEventListener('DOMNodeInserted', listener);
    });
  }

  function myclick() {
    return new Promise(resolve => {
      var a = document.querySelector('#dle-content > div.section > ul > li:nth-child(3)').click();
      resolve(a);
    })
  }


  async function myf() {
    let res0 = await myclick();
    let res1 = await wait('.cdn_download_item').then(() => {
      var elements = Array.from(document.querySelectorAll('.cdn_download_item span:first-child'));
      var linksArray = new Array();
      for (element of elements) {
        linksArray.push(element.innerText);
      }
      returnArray.push(linksArray);
    })

    let res2 = await returnArray;
    return res2;
  }

  return myf();
})();
  • Why are most of these promises? – evolutionxbox May 20 '22 at 08:11
  • I don't see anywhere you're using the result of `myf`, but wherever it is, you need to wait for the promise to be fulfilled. Some other notes: There's no reason for `myclick` to create or return a promise. There's no reason to `await` an array (`returnArray`); arrays are not promises. It makes some sense for `wait` to return a promise, but A) [DOM mutation events](https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent) were deprecated well over a decade ago and B) You probably want to remove that event listener when you find the element. I suggest reading up on promises/async/await. – T.J. Crowder May 20 '22 at 08:16
  • @AndersonB - Please don't make assumptions, it's **very** rude to accuse people of poor behavior you have no way of knowing about. I did indeed read your question until the end, and it's unclear, but given your description it's overwhelmingly likely that you're not correctly using the promise your anonymous outer `async` function returns; see the linked questions' answers. If you clarify the question and that turns out not to be the case, your question can be reopened. – T.J. Crowder May 20 '22 at 08:17

0 Answers0