0

So I want to return a string from within a function that gets formed two AJAX calls deep. I can figure out a messy way of doing this, but I imagine there is a better way to do this?

function fetchAndFillTemplate(options) {
  $.getJSON(options.data, {}, function(data, status) {      
    $.get(options.template, function(template) {

      // this is the string I want to return when you call 'fetchAndFillTemplate'
      var rendered_template = Mustache.to_html(template, data);

    });
  });
}
dobus
  • 87
  • 8
  • I understand its a simple question, but I don't fully understand scope in javascript and am not sure how best to return a variable when doing an abstraction like this. Any suggestions? – dobus Jan 09 '14 at 05:19
  • You need to use a callback, just like you do with your AJAX calls. – Jared Jan 09 '14 at 05:19
  • @user3159196 my suggestion is that you take the time to read and understand the question I linked. – Matt Ball Jan 09 '14 at 05:20
  • I am already using a callback for both AJAX calls, how would I use a callback for the original function? – dobus Jan 09 '14 at 05:21

1 Answers1

4

You can't return that value because it's an asynchronous task.

A workaround without using Promises would be:

function fetchAndFillTemplate(options, callback) {
  $.getJSON(options.data, {}, function(data, status) {      
    $.get(options.template, function(template) {

      // this is the string I want to return when you call 'fetchAndFillTemplate'
      var rendered_template = Mustache.to_html(template, data);
      callback(rendered_template);
    });
  });
}

As you can see, we added a new parameter callback, that will be a function;

So, then, instead of calling like this:

var tpl = fetchAndFillTemplate(options);

You'd have to do:

fetchAndFillTemplate(options, function(rendered_template){
    var tpl = rendered_template;
});

Hope this helps. Cheers

PS: Well, there's a way to return the final value, by making the ajax calls sync, but I won't post it because it's not recommended at all (blocks the UI).

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • It'd be an even better answer if you explained/provided a resource explaining what async means. :) – Jared Jan 09 '14 at 05:20
  • Awesome, thanks. This is what I was looking for. I have been working mostly with Ruby until lately and am getting tripped up in javascript. I'll accept the answer in 3 minutes ask SO commands. – dobus Jan 09 '14 at 05:25