Question

When running get_style_guide_version() the console will return the expected data, but what prints in the browser is undefined. Why is that?

function get_style_guide_version() {

    var jqxhr = $.getJSON( '/package.json', function() {
    })
    .done(function(data) {
        output = data.version;
        console.log(output);
        return output;
    });

}
$( document ).ready(function() {
    document.write(get_style_guide_version());
});
Was it helpful?

Solution 2

On the document ready function you are trying to write the results of get_style_guide_version(), which is running an async process

So the function completes before the async has returned so that wont work.

What you should do is have another function that is called manually that writes to the document and is called when the .done promise fires.

function get_style_guide_version() {

var jqxhr = $.getJSON( '/package.json', function() {
})
.done(function(data) {
    output = data.version;
    console.log(output);
    write(output);
});

}
$( document ).ready(function() {
document.write(get_style_guide_version());
});

function write(val){
    document.write(val);
}

or

function get_style_guide_version(done) {

var jqxhr = $.getJSON( '/package.json', function() {
})
.done(function(data) {
    output = data.version;
    console.log(output);
    done(output);
});

}
$( document ).ready(function() {
   document.write(get_style_guide_version(function(val){
      document.write(val);
   }));
});

OTHER TIPS

There is two issues with the code:

  • The function actually returns nothing. Your return statement is inside the .done() function of your ajax request.
  • That request is done asynchronously and will most certainly not have been completed before your get_style_guide_version completes.

If you did the document.write part instead of the console.out, it would work as expected.

Simple answer is, its an asynchronous request, function wont wait for the success event to happen..

When you write return output, you are returning in the done() callback. Not in the get_style_guide_version method.

You should use another callback to write the output in your browser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top