我正在使用对此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()循环内的异步调用中使用promise的最佳方法是什么?使用q.all()吗?

最佳答案

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

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失败,则所有失败的Q.all将在出现错误后立即reject而不是resolve ...您可能想使用q.allSettled代替-这将等待使所有.get完成(成功或失败),您可以在.then代码中检查失败。请参阅q.allSettled的文档

09-25 17:11
查看更多