我无法理解回调。这是一个简单的例子来展示我对此感到困惑。在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
答案 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);