Unsure why variable is undefined. Possible scope issue?

前端 未结 4 643
夕颜
夕颜 2021-01-26 13:28

If you look at the function below, on line 11 where it alert(template);. It prints undefined. If I alert(template); inside the ajax succes

4条回答
  •  星月不相逢
    2021-01-26 14:07

    ajax is asynchronous. to explain in simple terms: ajax works like it runs on a separate "thread", processing in the background while your code continues.

    by the time you called load_template(), it alerts after $.ajax() was called but before the template was returned thus undefined.

    what you can do is this so everything runs after a success has been returned:

    function load_template(path, data, callback){
    
        $.ajax({
            url: path,
            success: function(uncompiled_template){
                var template = Handlebars.compile(uncompiled_template);
    
                alert(template);    
    
                if(callback){
                    callback(template, data);
                }else{
                    return template(data);
                }
            }
        });
    }
    

提交回复
热议问题