JS / React - 函数在完成之前返回undefined

时间:2017-11-23 01:55:18

标签: javascript reactjs ecmascript-6 es6-promise

在我的React应用程序中,我创建了一个函数,用于从包含图像数据的数组中获取特定图像大小,例如mimetype,可用大小,路径等。

export default function getImageSize(image, size) {

    // Map through each available size for the image
    image.sizes.forEach((v, i) => {

        // Return the fullpath if there is a match for the requested size
        if (v.type === size) {
           return v.fullpath;
        }

    });

}

我用以下方法调用此函数:

let smallImageSize = getImageSize(data.images[0], 'small');

在我的页面中使用它:

<img alt="thumbnail" src={smallImageSize} />

正如你可能猜到的那样(对于经验更丰富的人),我的函数返回undefined,因为函数内部的循环在函数完成之前没有返回。

我的问题是,如何确保我的函数在渲染函数继续之前的其他任何内容之前等待返回值?是唯一的使用承诺吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

问题出在你的forEach循环中。从forEach循环返回一个值实际上并没有做任何事情。

您需要使用find代替:

export default function getImageSize(image, size) {

    // Map through each available size for the image
    const img = image.sizes.find(v => {

        // Return the image if there is a match for the requested size
        if (v.type === size) {
           return true;
        }

    });

    // img can be undefined if it does not exist
    return img && img.fullpath;
}