如何在函数返回后执行回调

时间:2015-08-06 18:44:24

标签: javascript

我无法理解回调。这是一个简单的例子来展示我对此感到困惑。在getData返回后需要调用回调printData。

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

1 个答案:

答案 0 :(得分:3)

您可以将您的功能更新为以下

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);

供参考 - https://jsfiddle.net/xsrLeo9u/2/