承诺正在返回[对象承诺] [英] Promise is returning [object Promise]

查看:45
本文介绍了承诺正在返回[对象承诺]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行基本检查,以查看图像是否为视网膜并具有纵向比率.我的所有检查功能都工作得很好.我的问题是,在应该返回从检查中获得的布尔值的最终函数中,它正在返回[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.

当我运行.then(res => console.log(res))时,它会输出我的布尔响应,但是返回承诺的函数getImageMeta()只会返回[object 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)} />

推荐答案

这是预期的结果.返回new Promise对象时,它将始终是一个Promise对象(字符串化时为[object Promise]).

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

您可以使用.then方法(或在async函数中使用await)访问promise的结果.当/如果结果可用,则调用.then回调,这将在您调用resolve之后发生,或者如果诺言已经被解决,则会很快调用它.

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

这篇关于承诺正在返回[对象承诺]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆