[英]Calling a function twice in node.js
我有一個叫getX的函數,它帶有四個參數,分別是計數器,用戶列表,變量x和響應。 我想做以下事情。
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})
}
}
當然,此代碼將無法正常工作,因為我將從每個函數調用中發送兩次響應
無論如何,我可以一次完成這兩個函數的調用嗎?
如果您希望避免多次通話,可以嘗試執行以下操作:
指針
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}) } }
如果我理解正確,您的res.send被調用兩次,但這不是因為您在函數中多次調用了detectX,而是因為您的內部if / else錯誤。如果您輸入else,那么您還將調用第二個detectX所以您應該將兩個電話完全分開
if(users.indexOf(x)){
detectX(++i, users, x, res);//or whatever you have to do
} else{
detectX(i, users, 0, res);
}
如果我可能還要指出另一件事,我將重構該函數,使其返回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})
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塊中的self調用之后添加了return語句。
好吧,我設法通過定義一個全局數組解決了這個問題,並將其命名為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});
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.