27

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)} />
2
  • Have a look at MDN - Using Promises to learn more about promises. .then(res => res) is redundant, you don't need it. "My issue is that in the final function that is supposed to return the boolean" That's not possible. You cannot convert an asynchronous process into a synchronous one. Oct 12, 2017 at 22:51
  • I got this error when I forgot to mention "await" besides service call in the async function. It got resolved after adding it. Jul 23, 2020 at 16:18

6 Answers 6

45

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

6

The basic idea of a promise is that it gives you something to return right away even if it won't resolve until later. It represents its eventual value. So getImageMeta () is immediately returning the promise even though it has not resolved.

Once you have the promise returned by getImageMeta () you can use its then() to wait for the final boolean, which will come on the next event loop cycle at the earliest.

With your current code you are saving the promise returned by getImageMeta() to checkIfPortrait. So now checkIfPortrait holds this promise and you can call then() on it. Since you are exporting checkIfPortrait you will probably end up calling then on the module that imports it:

 // import checkIfPortrait
checkIfPortrait(src)
.then(ret_val => {
   //you can access boolean here in ret_val
})
1
  • Sorry @BradyEdgar - I see what's going on now. I didn't realize you were saving the result to checkIfPortrait and exporting that. checkIfPortrait with hold a reference to the promise. You'll call then() on checkIfPortrait. But the way promises work you can't access the value directly because that will be too soon. You need to deal with it in the then() callback.
    – Mark
    Oct 12, 2017 at 23:39
3

Try this,

function axiosTest() {
    axios.get(url)
        .then(response => response.data)
        .catch(error => error);
}

async function getResponse () {
        const response = await axiosTest();
        console.log(response);
}

getResponse()

It works, but each function where you want to get the response needs to be an async function or use an additional .then() callback.

function axiosTest() {
    axios.get(url)
        .then(response => response.data)
        .catch(error => error);
}

async function getResponse () {
        axiosTest().then(response => {
                console.log(response)
        });
}

getResponse()

If anyone knows a way to avoid this please do tell.

Also checkout Katsiaryna (Kate) Lupachova's article on Dev.to. I think it will help.

1

The issue is now resolved, thanks to everyone for the help. Like stated the issue was I was calling the promise's value before it could be resolved and had no way of updating that value after it had been resolved.

So what I did is made sure the image data was accessible before running the function. Then once I had a resolved promise it then update the image data to show whether it is portrait or not.

So the final code looks like this:

const enhance = lifecycle({
   componentWillMount: function () {
     Object.keys(this.props.media).map((i) =>
       checkIfPortrait(this.props.media[i].image)
         ? this.props.media[i].isPortrait = true
         : this.props.media[i].isPortrait = false
       );
   }
 })

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 }

<img src={media[i].image} alt={media[i].alt} data-portrait={media[i].isPortrait} />
0

your function return promise so you should call it as promise

   <img src={media[i].image} alt={media[i].alt} data-portrait={checkIfPortrait(media[i].image).then(result=>result})};
0

Promise is returning [object Promise] then it returns a null value. check the collection of mongo DB and ensure accessing path is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.