简体   繁体   中英

resolve() executes but promise not resolves as expected

I have such code: (I put here the whole code in order not to miss anything)

let updateCoverLoaded;

function coverLoaded(cover){
  clearInterval(updateCoverLoaded);  
  updateCoverLoaded = setInterval(() => coverLoaded(cover), 25);
  const coverSelector = $(`[aria-label="${cover}"]`).find("image")[0];
  return new Promise(resolve => { 
    if(typeof coverSelector !== "undefined"){
       const coverSelectorSource = coverSelector.getAttribute("xlink:href");
       if(getCoverWidth(coverSelectorSource) !== 0) {
          clearInterval(updateCoverLoaded);
          setTimeout(() => { 
              player.SetVar(`${cover}`, true);
              setTimeout(() => player.SetVar(`${cover}`, false), 100);
              resolve();
          }, 100); 
       }
    }
  });
  
  function getCoverWidth(src) {
    const image = new Image();
    image.src = src;
    return image.naturalWidth;
  }
}

// Add SFX to cover entrance and exit
async function feedbackCover(){
  await coverLoaded('coverB');
  console.log('after resoving promise as expected!');
}

Although code reaches the player.SetVar( ${cover} , true); line of code and I'm sure that resolve() is executed the promise doesn't resolve and I can't see console.log('after resoving promise as expected;'); Why? it works in some other situations!

Note: The code actually waits for an element (an image) to load and then resolves the promise.

There are two possible problems, the first is that if the image isn't loaded yet it the first Promise doesn't resolve and all subsequent Promises are discarded, the second is that if coverLoaded is called again, the first promise will never resolve.

This should work as expected:

function coverLoaded(cover) {
  return new Promise((resolve) => {
    const updateCoverLoaded = setInterval(() => {
        const coverSelector = $(`[aria-label="${cover}"]`).find("image")[0];
        if (typeof coverSelector !== "undefined") {
          const coverSelectorSource = coverSelector.getAttribute("xlink:href");
          if (getCoverWidth(coverSelectorSource) !== 0) {
            clearInterval(updateCoverLoaded);
            setTimeout(() => {
              player.SetVar(`${cover}`, true);
              setTimeout(() => player.SetVar(`${cover}`, false), 100);
              resolve();
            }, 100);
          }
        }
    }, 25);
  });

  function getCoverWidth(src) {
    const image = new Image();
    image.src = src;
    return image.naturalWidth;
  }
}

// Add SFX to cover entrance and exit
async function feedbackCover() {
  await coverLoaded("coverB");
  console.log("after resoving promise as expected!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM