Javascript JS/React-函数在完成之前返回未定义

Javascript JS/React-函数在完成之前返回未定义,javascript,reactjs,ecmascript-6,es6-promise,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 ther

在我的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,因为函数中的循环在函数完成之前没有返回

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

感谢您的帮助。

问题在于您的forEach循环。从forEach循环返回值实际上没有任何作用

您需要改用“查找”:

问题在于您的forEach循环。从forEach循环返回值实际上没有任何作用

您需要改用“查找”:


我也有一个想法:在componentWillMount中呈现页面之前,使用这个函数并通过状态加载URL是否更好?我正在React中的渲染中运行此函数。您应该使用const foundSize=image.size.findimageSize=>imageSize.type==size;返回foundSize&&foundSize.fullpath;我们需要知道data.images[0]是什么,而不是forEach,因此,标题是错误的,es6 promise标记是不正确的,所以我有一个想法:在componentWillMount中呈现页面之前,使用此函数并通过状态加载URL是否更好?我正在React中的渲染中运行此函数。您应该使用const foundSize=image.size.findimageSize=>imageSize.type==size;返回foundSize&&foundSize.fullpath;而不是forEach。另外,我们需要知道data.images[0]是什么。事实上,函数getImageSize在整个过程完成后返回undefined,因此标题是错误的-es6 promise标记是未保证的完美答案,非常感谢您的帮助。这就是方法!我将把find添加到我的Javascript库中,并在将来使用它。干杯。完美的回答,非常感谢你的帮助。这就是方法!我将把find添加到我的Javascript库中,并在将来使用它。干杯
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;
}