Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript setTimeout-回调参数必须是函数_Javascript_Node.js_Callback_Settimeout - Fatal编程技术网

Javascript setTimeout-回调参数必须是函数

Javascript setTimeout-回调参数必须是函数,javascript,node.js,callback,settimeout,Javascript,Node.js,Callback,Settimeout,我的代码一直在工作,直到我将node.js更新到8.11.3版 现在,在尝试使用setTimeout调用函数时,我总是会遇到错误“回调参数必须是函数” function testFunction(itemid, price) { var url = 'https://example.com'; var options = { method: 'get', url: url } request(options, function (err, res, body) {

我的代码一直在工作,直到我将node.js更新到8.11.3版

现在,在尝试使用setTimeout调用函数时,我总是会遇到错误“回调参数必须是函数”

function testFunction(itemid, price) {

  var url = 'https://example.com';
  var options = {
  method: 'get',
  url: url
  }

  request(options, function (err, res, body) {
    var response = JSON.parse(body);

     if(response.status == 'fail'){
        setTimeout(testFunction(itemid, price), 100);
     }
  })

}

setTimeout
的回调参数必须是函数。这样写吧。没有测试,但它应该工作

function testFunction(itemid, price) {

    var url = 'https://example.com';
    var options = {
        method: 'get',
        url: url
    }

    request(options, function (err, res, body) {
        var response = JSON.parse(body);
        if(response.status == 'fail'){
            setTimeout(function () {
                testFunction(itemid, price);
            }, 100);
        }
    })
}

Q:我在尝试使用setTimeout调用函数时遇到错误“回调参数必须是函数”。为什么?

A:
设置超时(testFunction(itemid,price),100)
您意外地推送了
testFunction
的输出作为
setTimeout
的第一个参数,它被认为是
函数
,因此出现了错误

您可以做的是,传入一个函数,然后从那里递归调用
testFunction

示例:

功能测试(项目ID、价格){
log(“hello=>”+itemid+,“+price”);
如果(价格<50){
setTimeout(()=>{test(itemid,price+10)},100);
}
}
test(100,10)
是,setTimeout()需要第一个参数作为回调函数。 我们可以在这里使用es6 fat arrow函数 你可以试试这个

setTimeout(() => testFunction(itemid, price), 100);

希望这有帮助

@keyur是正确的。根据setTimeout函数,将要执行的函数的名称作为第一个参数,以毫秒为单位的延迟作为第二个参数,然后是传递给函数的任何参数

例如:

setTimeout(testFunction, 100, itemid, price);

代码从未按预期工作,仅供参考。同意,@MHH,您可能只是没有注意到
testFunction
在100毫秒后没有被调用,而是立即被调用–您没有将函数
testFunction
作为参数传递给
setTimeout
,而是调用它的结果。升级到节点8.11.3暴露了您的错误,因为它不允许您传递任何东西,只允许传递一个函数。它总是需要一个函数作为回调参数—它不允许
setTimeout()
是一种eval形式,它是故意从节点实现中删除的。@estus对此不感兴趣。取消那条线。