0

I want to get some value from my callback. Yes this was asked a lot of times in SO. But I can't find any solution.

    dostuff = function(callback) {

        $.ajax({
            type: 'GET',
            url: filepath,
            success: function(data) {
                var value = data.split("\n");
                var line = Math.round(Math.random() * (value.length - 1)) + 1;
                callback(value[line]);
            }
        });
    }


function myCallback(line){
    console.log(line);
}


obj.dostuff(myCallback);

That works fine and logs the value. But I want the code to look something like that:

function myCallback(line){
    return line;
}

console.log(obj.dostuff(myCallback));

But that logs "undefined". I don't get it.

Paili
  • 825
  • 5
  • 18
  • 30
  • That because `dostuff` doesn't return anything. – vallentin Mar 16 '17 at 10:58
  • that should console the line. Maybe it not goes to the success... try check `.error` see whats happens. – vaso123 Mar 16 '17 at 10:59
  • no @vaso123, it should log undefined, as Vallentin says, the doStuff() function doesn't return anything – Stu Mar 16 '17 at 11:01
  • 2
    You cannot return something *synchronously* ("right now") when the value is only available *asynchronously* ("sometime later"). Anything that touches asynchronous code must itself also be asynchronous. – deceze Mar 16 '17 at 11:04
  • @Stu Let's read that code together. A `dostuff` function called with a callback parameter. In this, an ajax calls happens. When ajax call is success, that should call the callback. In our case the callback is the `myCallback` with a parameter `line`. When this happens, the only job is the `myCallback` is to `console.log` the line. I assume that OP want to return from there, but get no value. This is why he try to console.log, to debug where is the problem. If it is not happens, I think there is something wrong with the ajax call. This is why I suggested that check the `.error` callback. – vaso123 Mar 16 '17 at 11:39
  • @vaso123, yes the `dostuff()` function returns nothing, so the value that is passed to `console.log(obj.dostuff(myCallback));` is nothing (undefined), it doesn't pass the value of the callback, it passes the return value of `doStuff()` i.e. nothing (which is why it returns undefined). – Stu Mar 16 '17 at 11:42
  • @Stu My fault, I just totally skiped the second part of the question. – vaso123 Mar 16 '17 at 11:47

0 Answers0