jQuery.when不等待完成

时间:2015-02-08 00:45:37

标签: jquery promise

我觉得我没有在这里得到概念承诺。我试图在文件中使用外部css并将其附加到html。然后我想对这些内容做点什么。我在这里做错了什么?这就是我在fla and reading reading reading reading reading and for for for for for for for for for。<<<<<<<<<<<<<<<

<script type="text/javascript">

        $(function() {
            $.when(convertPageCssToInlineStyle()).then(
                alert(document.documentElement.outerHTML)
            );


        });

        var convertPageCssToInlineStyle = function() {
            var links = $("html").find("link[rel=stylesheet]");

            links.attr("href", function(i, value) {
                if (!window.location.origin)
                    window.location.origin = window.location.protocol + "//" + window.location.host + value;

                $.when(
                    $.get(window.location.origin, function(response) {
                        $('<style />').text(response).appendTo($('head'));
                    })
                );

            });
        };
    </script>

2 个答案:

答案 0 :(得分:3)

我能够通过将我的promises映射到数组来解决这个问题,然后使用This question's answer中的代码一次性处理它们

<script type="text/javascript">
    $(function() {

        var links = $("html").find("link[rel=stylesheet]");
        var newLinks = [];

        if (!window.location.origin)
            window.location.origin = window.location.protocol + "//" + window.location.host;

        links.attr("href", function(i, value) {
            newLinks.push(window.location.origin + value);
        });

        var promises = $.map(newLinks, function(value) {
            return $.get(value, function(response) {
                $('<style />').text(response).appendTo($('head'));
            });
        });

        $.when.apply($, promises).then(function() {
            console.log(document.documentElement.outerHTML);
        });
    });

</script>

答案 1 :(得分:1)

您的convertPageCssToInlineStyle函数必须返回一个承诺。现在它没有返回任何东西。

像这样......

    $(function() {
        $.when(convertPageCssToInlineStyle()).then(
            alert(document.documentElement.outerHTML)
        );


    });

    var convertPageCssToInlineStyle = function() {
        var links = $("html").find("link[rel=stylesheet]");
        var deferred = $.Deferred();
        links.attr("href", function(i, value) {
            if (!window.location.origin)
                window.location.origin = window.location.protocol + "//" + window.location.host + value;

            $.when(
                $.get(window.location.origin, function(response) {
                    $('<style />').text(response).appendTo($('head'));
                    deferred.resolve();
                })
            );
        });
        return deferred.promise();
    };
</script>