Search code examples
jqueryajaxsvg.whenasynchronous-javascript

How to make function work after another (which contains ajax request)


I have 2 finctions: first load svg on page, second change color of certain <path> in some svg.

This functions looks like:

get_svg_part(category,position,part_name); -- contains ajax

svg_part_color(category,position,color,parameter); -- need execute it after get_svg_part()

I have cases when i neen just load svg and not change color, in another cases i need load svg and change color of couple in it. That's why i not used success or complite in ajax. Also i need do it on page loading so i put all (2 functions and call) before jQuery(document).ready() (if this information is necessary).

I tried to do it by $.when and .then but this has no effect:

$.when(get_svg_part('accent','bottom','😊 U+1F60A')).then(svg_part_color('accent','bottom','#FF7892',0));

Maybe i need make svg_part_color(); in some sense asynchronous too? If so, then how?

Question: How to make function work after another (which contains ajax request)?

Cool if this will work like:

get_svg_part('accent','bottom','😊 U+1F60A');
svg_part_color('accent','bottom','#FF7892',0);

$.when(get_svg_part()).then(svg_part_color()); // just set a rule and not execute function here

// or maybe put this rule in svg_part_color() function


Update: get_svg_part code:

function get_svg_part(cathegory,position,part_name){ 
   $.ajax({
    		url: "img/icons/parts/"+cathegory+"/"+position+"/"+part_name+".svg",
    		type: 'GET',
    		dataType: 'html',
    		success: function( data ){
    			let rate_block_rated = movie_block.find('.movie_rating.rated'); //rate_block_rated
    			let svg_symbol = rate_block_rated.find(".composite_rate svg ."+cathegory+"."+position);
    			// prepend (insert) data to svg_symbol (accent bottom),
    			// then find inserted svg, and delete svg tag (unwrap path)
    			svg_symbol.prepend(data).find('svg').children().unwrap();

    		}
    });					
};


Solution

  • So long as your first function returns a promise related to the ajax then you can do something like the following:

    function get_svg_part(a, b, c){  
    
        // return the jQuery `$.ajax()`, `$.post()`, `$.getJSON()` 
        // or whatever method you are using    
        return $.ajax({/* options */})
    
    } 
    

    Usage:

    get_svg_part().then(function() { 
       svg_part_color('accent','bottom','#FF7892',0);
    })