Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - Promise is returning [object Promise]

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

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

1 Reply

0 votes
by (71.8m points)

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"}
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...