从延迟嵌套函数返回值

Return value from deferred nested function

本文关键字:返回值 函数 嵌套 延迟      更新时间:2023-09-26

我正在编写一个缓存函数,它将不可见的内容加载到DOM中,以便能够正确计算div大小(包括图像)。缓存完成后,我使用jQuery的延迟对象来运行一个函数。

我遇到的问题是,一旦缓存功能完成,我就无法计算如何返回props对象。底部的return props显然是我想要返回属性对象的地方,但它返回的是未定义的,因为在调用返回时_obj函数尚未完成。

我的complete函数在底部附近正确地记录了props对象(包括cacheHeightvar),但我不知道如何从延迟函数返回props对象。我想做一些类似return _obj(content).done(complete);的事情,但很明显,它返回的是延迟对象,而不是完整函数的返回。

    cache : function(content) {
        // Vars
        var props;
        // Deferred switch
        var r = $.Deferred();
        /*
         * Cache object
         */
        var _obj = function(content) {
            cacheHeight = 0;
            cache = document.createElement("div");
            cache.style.visibility = "hidden";
            $(cache).css("position", "fixed"); // prevents parent's size being affected
            $(cache).append(content);
            $(contentWrapper).append(cache);
            children = $(cache).children();
            // Image loader
            var imgs = $(cache).find('img'),
                img_length = imgs.length,
                img_load_cntr = 0;
            if (img_length) { //if the $img_container contains new images.
                imgs.on('load', function() { //then we avoid the callback until images are loaded
                    img_load_cntr++;
                    if (img_load_cntr == img_length) {
                        remaining = children.length;
                        $.each(children, function(index, value) {
                            --remaining;
                            cacheHeight = cacheHeight + parseInt($(value).outerHeight(false));
                            if (remaining == 0) {
                                props = {
                                    height : cacheHeight
                                }
                                r.resolve();
                            }
                        });
                    }
                });
            }
            return r;
        };
        /*
         * Return cached object data
         */
        var complete = function () {
            console.log(props); // Correctly logs props object
        };
        // Resolve when finished
        _obj(content).done(complete);
        console.log(props); // Logs props as undefined (not good)
        // Return?!?!
        return props;
    }

如果您将函数作为回调传递到缓存参数中以访问props变量,会怎么样。我想知道你是否会在布景前归还道具。

当调用解析时,它可以接受参数,所以应该这样调用它:

r.resolve(args);

然后完成会自动将其转移到您的回调:

         /*
         * Return cached object data
         */
        var complete = function (args) {
            //use args as you see fit
            ready = true;
        };

有关更多详细信息:http://api.jquery.com/deferred.resolve/