2017-08-08 96 views
0

我有一个函数让我们称它为getX,它带有四个参数,它们是计数器,用户列表,变量x和响应。我想要做类似下面的事情。在node.js中调用两次函数

let detectX = function(i, users, x, res){ 
    if(i<users.length){ 
     //do something with x 
     if(users.indexOf(x)){ 
      //do something 
     } else{ 
      detectX(i, users, 0, res); 
     } 
     detectX(++i, users, x, res); 
    } 
    else{ 
     res.send({x}) 
    } 
} 

当然,我会从每一个函数调用

两次发送响应这个代码将不能工作,反正我可以做一个这两个函数调用?

+2

我不明白这两个函数你想要打两次。 – Slavik

+0

首先,'users.indexOf(x)'是不完整的。使用'users.indexOf(x)> = 0'。其次,对于2个函数调用,如果'x'不在'users'中,那么可以使用局部变量来保存必要的值 – Rajesh

+0

,这确实是'detectX'将被调用两次。但目前还不清楚你想做什么...... – ValLeNain

回答

0

你可以尝试这样的事情,如果你想避免多次电话:

指针

  • indexOf返回数值。如果未找到,则找到-1并找到索引。使用if(users.indexOf(x))不正确,因为如果找到x作为第一个元素,并且找不到值,它将会失败。
  • 如果您希望避免对同一个函数进行多次调用,您可以创建表示参数的局部变量并根据条件处理它们,最后将它们传递给单个函数调用。

let detectX = function(i, users, x, res){ 
 
    if(i<users.length){ 
 
     // Assign default values to them to avoid `else` processing 
 
     let n = i, 
 
      newX = 0; 
 
     //do something with x 
 
     if(users.indexOf(x) >= 0){ 
 
      //do something 
 
      n++; 
 
      newX = x; 
 
     } 
 
     detectX(n, users, newX, res); 
 
    } 
 
    else{ 
 
     res.send({x}) 
 
    } 
 
}

+0

**注意:**这个回答只针对重构多个'directX'的代码。如果有任何遗漏或不正确的地方,请与您的投票一起评论。 – Rajesh

0

如果我理解正确的,你的res.send被调用两次,但因为你调用detectX不止一次在你的函数,这不是,而是因为你的内心的if/else是wrong..if你进入别人,那么你也叫第二detectX所以你应该分开2个呼叫完全

if(users.indexOf(x)){ 
    detectX(++i, users, x, res);//or whatever you have to do 
} else{ 
    detectX(i, users, 0, res); 
} 

如果我可以指出一两件事,我会重构FUNC重刑所以它返回x,然后在响应发送X,像这样

let detectX = function(i, users, x){ 
    if(i<users.length){ 
     //do something with x 
     if(users.indexOf(x)){ 
      return detectX(++i, users, x); 
     } else{ 
      return detectX(i, users, 0); 
     } 

    } 
    else{ 
     return x 
    } 
} 

let detected = detectX(i,users,x) 
res.send({detected}) 
0
let detectX = function(i, users, x, res){ 
    if(i<users.length){ 
    //do something with x   
    if(users.indexOf(x)){ 
    //do something 
    } else{ 
     detectX(i, users, 0, res); 
     return; // here 
    } detectX(++i, users, x, res); 
    } else{ 
    res.send({x}) 
    } 
} 

我想这是你在找什么。在else块中的自我调用之后添加了一个return语句。

0

嗯,我设法通过定义一个全局数组来解决这个问题,我把它命名为functionsStack和我推的功能之一,它,直到我完成了循环

global.functionsStack = [] 

let detectX = function(i, users, x, res){ 
    if(i<users.length){ 
     //do something with x 
     if(users.indexOf(x)){ 
      //do something 
     } else{ 
      functionsStack.push({"i":i, "users":users, x:"0"}); 
     } 
     detectX(++i, users, x, res); 
    } 
    else{ 
     if(functionsStack.length>0){ 
      var currentFunction = functionsStack[0]; 
      functionsStack.splice(0,1); 
      detectX(currentFunction.i, currentFunction.users, currentFunction.x, res); 
     } else{ 
      res.send({x}); 
     } 
    } 
}