2

I can't get my head around callbacks. Here is a simple example to show what I'm confused about. The callback printData needs to be called after getData has returned.

function data(cb) {

   var myData = getData();  
    cb(myData);
}

function printData(data) {

    console.log("printing " + data)   
}

function getData () {

    console.log("getting data");

    setTimeout(function(){
        console.log("finishing data");
        return "this is the data"
    }), 3000;
}

data(printData);

//OUTPUT

//getting data
//printing undefined
//finishing data

JSFIDDLE

benc
  • 1,978
  • 3
  • 15
  • 22
  • 2
    `getData` does return immediately. The `return` in the `setTimeout` callback is useless. `getData` needs to take a callback as well. – Bergi Aug 06 '15 at 18:46
  • Take a look at this: http://stackoverflow.com/a/5520190/185672 – Phil Aug 06 '15 at 18:47
  • Why do you need a callback there? It doesn't seem to be useful at all in your code. – alcfeoh Aug 06 '15 at 18:48

1 Answers1

4

You can update your function to following

function data(cb) {

   getData(cb);  // pass the callback function

}

function printData(data) {

    console.log("printing " + data)   
}

function getData (cb) {

    console.log("getting data");

    setTimeout(function(){
        console.log("finishing data");
        cb("this is the data"); // call the callback function
        //return "this is the data" // this return is useless, remove it
    }), 3000;
}

data(printData);

For reference - https://jsfiddle.net/xsrLeo9u/2/

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59