在jQuery .each中将多个.get()转换为q promise

时间:2015-10-31 00:24:15

标签: javascript jquery promise q

我正在使用这个question的优秀答案将svg图像转换为内联html。

该函数查看容器或正文,找到每个.svg图像 并将它们转换为内联html。

但是,它使用$.get()调用来检索svg文件 这使得函数异步。

我想将函数转换为promise,以便在运行其他内容之前等待它完成(比如在新的内联html中添加或删除类等)

我目前的尝试是这样的:

util.convertSvgImages = function(container) {
    var deferred = Q.defer();
    container = typeof container !== 'undefined' ? container : $("body");

    var getsToComplete = jQuery('img.svg', container).length;   // the total number of $get.() calls to complete within the $.each() loop
    var getsCompleted = 0;                                      // the current number of $get.() calls completed (counted within the $get.() callback)

    jQuery('img.svg', container).each(function(index) {
        var img = jQuery(this);
        var imgID = img.attr('id');
        var imgClass = img.attr('class');
        var imgURL = img.attr('src');
        jQuery.get(imgURL, function(data) {
            getsCompleted += 1;

            var svg = jQuery(data).find('svg');                         // Get the SVG tag, ignore the rest

            if (typeof imgID !== 'undefined') {                         // Add replaced image's ID to the new SVG
                svg = svg.attr('id', imgID);
            }

            if (typeof imgClass !== 'undefined') {
                svg = svg.attr('class', imgClass + ' replaced-svg');    // Add replaced image's classes to the new SVG
            }

            svg = svg.removeAttr('xmlns:a');                            // Remove any invalid XML tags as per http://validator.w3.org

            svg.attr('class', img.attr("data-svg_class") + " svg");     // add class to svg object based on the image data-svg_class value

            $('rect', svg).attr("stroke", "").attr("fill", "");
            $('line', svg).attr("stroke", "").attr("fill", "");
            $('path', svg).attr("stroke", "").attr("fill", "");
            $('polyline', svg).attr("stroke", "").attr("fill", "");
            $('polygon', svg).attr("stroke", "").attr("fill", "");
            $('circle', svg).attr("stroke", "").attr("fill", "");

            img.replaceWith(svg);                                       // Replace image with new SVG

            if (getsCompleted === getsToComplete){
                deferred.resolve('OK');
            }
        }, 'xml');
    });
    return deferred.promise;
};

$.each()循环内的异步调用中使用promises的最佳方法是什么?使用q.all()

1 个答案:

答案 0 :(得分:0)

jQuery.get返回一个promise,因此,您可以使用它和jquery.map来创建一个可以在q.all(或Promise.all中使用)的promises数组

util.convertSvgImages = function(container) {
    // ... snip
    var promises = jQuery('img.svg', container).map(function(index) {
        // ... snip
        return jQuery.get(imgURL, function(data) {
            // ... snip
        }, 'xml');
    });
    return q.all(promises);
};

使用

util.convertSvgImages().then(.....)

注意:如果任何.get失败,一旦所有.gets完成,Q.all会在失败后立即reject 而不是resolve。{您可能希望使用q.allSettled - 这将等待所有.get完成(成功或失败),您可以检查.then代码中的失败。请参阅q.allSettled

的文档