roll()函数运行良好,但是当我试图获得回调时它会抛出错误:回调不是函数
var speed = 300;
function roll(callback) {
if (typeof callback === "function") {
console.log('callback is function!'); //yes
}
if (speed < 1000) {
speed += 50;
setTimeout(roll, 1000); //increase speed
} else if (speed >= 1000) {
console.log('finished');
return callback(true); //problem here?
}
}
roll(function(callback) {
console.log(callback); //callback is not a function
});
答案 0 :(得分:5)
问题的根本原因在于:setTimeout(roll, 1000)
。
roll
被callback
调用但 没有 setTimeout
功能。
var speed = 300;
function roll(callback) {
console.log('callback', callback);
if (speed < 1000) {
speed += 50;
setTimeout(function() {
roll(callback); //pass the callback
}, 1000); //increase speed
} else {
console.log('finished');
callback(true); //removed un-wanted `return`
}
}
roll(function(result) { //renamed parameter
console.log(result);
});
答案 1 :(得分:1)
当此部分代码触发时,roll
未获得callback
参数:
setTimeout(roll, 1000); //increase speed
所以当执行这部分代码时:
return callback(true); //problem here?
// ^^^^^^^^^^^^^^
callback
为undefined
,因此不是function
。您可以通过执行以下操作来避免此错误:
else if (speed >= 1000) {
console.log('finished');
if(typeof callback === 'function'){
return callback(true);
}else{
// do what you want here if callback is undefined
}
}