下面有我的代码,根据myArray.length多次调用了doProcess,现在的问题是 我可以跟踪doProcess是否被调用了几次,我尝试使用计数器但似乎没有任何想法?不用担心doprocess被执行了,我已经使它成为可能,我只想跟踪doprocess被调用了多少次。
doProcess(myArray, 0);
function doProcess(myArray, index) {
if (myArray.length === index) {
return;
}
data["users"] = array
data["random_code"] = myArray[index];
QuestionaireService.share_questionaire(me, data).then(function (response) {
if (response.status == "200") {
doProcess(myArray, ++index);
count++;
}
});
console.log("count", count)
}
答案 0 :(得分:2)
根据上述信息。要求仅打印counter
一次。将日志记录置于if
状态。
尝试此代码。
var count = 0;
doProcess(myArray, 0);
function doProcess(myArray, index) {
if (myArray.length === index) {
console.log("count", count)
return;
}
data["users"] = array
data["random_code"] = myArray[index];
QuestionaireService.share_questionaire(me, data).then(function (response) {
if (response.status == "200") {
doProcess(myArray, ++index);
count++;
}
});
}
答案 1 :(得分:0)
为什么不尝试在函数外部设置变量,然后在内部递增变量:
let counter = 0
doProcess(myArray, 0);
function doProcess(myArray, index) {
counter += 1
if (myArray.length === index) {
return;
}
data["users"] = array
data["random_code"] = myArray[index];
QuestionaireService.share_questionaire(me, data)
.then((response) => {
if (response.status == "200") {
doProcess(myArray, ++index);
count++;
}
});
console.log("count", count)
}
console.log("counter", counter)
答案 2 :(得分:0)
您的计数器增加得很好。但是由于您在doProcess
函数内部使用了异步调用,所以问题在于何时打印计数器?
因此您必须在打印时打印它,否则它不会增加更多(因此,当您不再调用doProcess()时)。
尝试类似的东西:
doProcess(myArray, 0);
function doProcess(myArray, index) {
count++;
if (myArray.length === index) {
// Need to print it too if the process is over
console.log("count: ", count);
return;
}
data["users"] = array
data["random_code"] = myArray[index];
QuestionaireService.share_questionaire(me, data).then(function (response) {
if (response.status == "200") {
doProcess(myArray, ++index);
} else {
// Here, you know you are in the last call of doProcess()
console.log("count: ", count)
}
});
}