Javascript:回调不是一个功能

时间:2016-01-06 09:41:49

标签: javascript

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

2 个答案:

答案 0 :(得分:5)

问题的根本原因在于:setTimeout(roll, 1000)

rollcallback调用 没有 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?
//     ^^^^^^^^^^^^^^

callbackundefined,因此不是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
    }
}