morteza mortezaie
morteza mortezaie

Reputation: 1564

promise doesn't get rejected

I have created a promise that it's task is to ensure that specific tag exists on the page

and it is resolved only when tag exist => this work perfectly

and after 5 seconds if the tag don't get found it will be rejected => this part don't work

and after more that 5 seconds it doesn't get rejected !

this is my code , based on Jquery

function findCal() {
  return new Promise((res, rej) => {
    let flag = true
    const time0 = new Date().getTime() / 1000

    do {
      if ($('.ng-star-inserted .dp-material').length > 0) {
        flag = false
        res()
      }
      const time1 = new Date().getTime() / 1000
      console.log('time', time1 - time0)
      if (time1 - time0 > 5) {
        rej('Time out ; Please try again')

      }

    } while (flag)
  })
}


try {
  await findCal()

} catch (err) {

  alert(err)
}

Why promise reject don't work ?

Upvotes: 0

Views: 48

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

With the Mutation Observer API you can monitor any changes in DOM structure. In your case you want to know whenever a specific Node is added to the DOM.

In the snippet below we observe the <body> tag and all it's children for any changes. If you do know the container your target element is going to be in, then you could change the observed element to that container.

With setTimeout we wait 5 seconds before the Promise is rejected.

function findCal() {
  return new Promise((resolve, reject) => {
    const observer = new MutationObserver(mutations => {
      for (const { addedNodes } of mutations) {
        for (const node of addedNodes) {
          if (node.className === 'ng-star-inserted dp-material') {
            resolve();
          }
        }
      }
    });

    observer.observe(document.body, {
      subtree: true,
      childList: true
    });

    setTimeout(() => {
      observer.disconnect();
      reject();
    }, 5000);
  });
}

The function can be used in the same manner as you already implemented.

Upvotes: 1

Related Questions