0

This probably has to do with asynchronous JavaScript and I'm having quite a bit of trouble figuring it out.

//inside another method
var ret = helper(tone_analyzer, myText);
console.log('loggerTwo');

function helper(tone_analyzer, myText) {
    var b;
    tone_analyzer.tone({text: myText}, function(err, result) {
        console.log('loggerOne');
        b = JSON.stringify(result, null, 2);
    });
    console.log(b)
    return b;
}

Essentially, the output that I am getting is in ORDER 1) undefined 2) loggerTwo 3) loggerOne

Why is this happening?

EDIT: I have looked at the duplicate link and still cannot figure out where exactly this code would fit in

tone_analyzer.tone({text: myText}, function(err, result) {
        console.log('loggerOne');
        b = JSON.stringify(result, null, 2);
});

I've never used JavaScript before.

halfer
  • 19,824
  • 17
  • 99
  • 186
user41912
  • 557
  • 1
  • 6
  • 18
  • You are logging and returning `b` well before it is set in the asynchronous callback. – Phylogenesis Oct 12 '16 at 08:07
  • where would i return b such that i can return its appropriate value?? @Phylogenesis – user41912 Oct 12 '16 at 08:10
  • Look at the question that [this is marked a duplicate of](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). All your answers lie there. – Phylogenesis Oct 12 '16 at 08:23
  • @Phylogenesis I have been trying using that for quite some time, I'm completely new to JS, and I'm trying to do the without-jquery option. In particular, in that answer, where would this following code go? I can't seem to figure it out :/ tone_analyzer.tone({text: myText}, function(err, result) { console.log('loggerOne'); b = JSON.stringify(result, null, 2); }); – user41912 Oct 12 '16 at 08:41

0 Answers0