等待嵌套函数在返回之前完成

时间:2018-06-12 20:40:19

标签: javascript

刚开始我对javascript很新。

我正在使用库来调整图像大小。这里的问题是函数在库完成大小调整之前返回变量imgBlob,这导致imgBlob未定义"。

我正在使用以下代码:

        function resizeImage(fileInput) {
        var imgBlob;
        ImageTools.resize(fileInput.files[0], {
            width: 320, // maximum width
            height: 240 // maximum height
        }, function (blob, didItResize) {
            // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
            if (didItResize == true) {
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onloadend = function () {
                    imgBlob = reader.result; 
                }

            } else {
                // error message ?
            }

        });

        return imgBlob;
    }



    document.getElementById('verzenden').onclick = function() {
        var imgBlobs = [];

        var imgHuisnummerField = document.getElementById('imgHuisnummer');
        if (imgHuisnummerField.value != "") {
            imgBlobs.push(resizeImage(imgHuisnummerField)); //pushes "undefined" to the array.

        }

如何在返回imgBlob之前等待整个resizeImage函数完成? 我尝试过等待async,但是留下了一个“承诺”。它没有按预期工作。

异步尝试:

        async function resizeImage(fileInput) {
        var imgBlob;
        await ImageTools.resize(fileInput.files[0], {
            width: 320, // maximum width
            height: 240 // maximum height
        }, function (blob, didItResize) {
            // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
            if (didItResize == true) {
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onloadend = function () {
                    imgBlob = reader.result; 
                }

            } else {
                // error message ?
            }

        });

        return imgBlob;
    }

它返回一个未解决的承诺..

0 个答案:

没有答案
相关问题