Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to do a basic check to see if an image is retina and has a portrait ratio. I have all that checking functionality working perfectly fine. My issue is that in the final function that is supposed to return the boolean I get from my checks it is returning [object Promise]. I have no idea why this is not returning my boolean when I resolve the promise.

When I run .then(res => console.log(res)) it outputs my boolean response, but the function getImageMeta() that returns the promise just returns that [object Promise] which makes me think the promise isn't actually being resolved.

If I could get some assistance that would be great!

/************************************
   Check if image is retina portrait
************************************/
const checkIfPortrait = src => !isRetina(src) ? false : getImageMeta(src).then(res => res);
 const isRetina        = src => src.indexOf('@2x') !== -1;
 const isPortrait      = ({ naturalWidth, naturalHeight }) => naturalHeight > naturalWidth ? true : false;

 function getImageMeta (src) {
    const img = new Image();
    img.src = src;

    return new Promise((resolve, reject) => {
      return img.addEventListener("load", function () {
         return resolve(isPortrait(this));
      }, false);
    });
  }


 export { checkIfPortrait }

This is how I am calling the function:

<img src={media[i].image} alt={media[i].alt} data-portrait={checkIfPortrait(media[i].image)} />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is the expected result. When you return a new Promise object, it will always be a promise object ([object Promise] when stringified).

You access the result of a promise by using the .then method (or using await in an async function). Your .then callback is then called when/if the result is made available, which will happen after you call resolve, or if the promise was already resolved prior it will be called rather quickly.

function getImageMeta(src) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({metadata: `for: ${src}`});
        }, 100);
    });
}

getImageMeta('test.png').then(meta => {
    console.log(meta); // {"metadata": "for: test.png"}
});

(async () => {
    const meta = await getImageMeta('test.png');
    console.log(meta); // {"metadata": "for: test.png"}
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...