gpt4 book ai didi

javascript - 需要根据条件再次循环javascript

转载 作者:行者123 更新时间:2023-11-28 07:59:54 24 4
gpt4 key购买 nike

嗨,我正在制作一个 javascript 脚本,现在它变得非常难以编辑,并且对其他人来说很难理解,我将其放在这里希望有人能够理解它并提供一些建议或帮助

function fetchMember(id, select, sitename, total) {
return function() {
progress();
$.ajax({
type: 'POST',
url: "script.php",
data: $("#fetch").serialize() + "&id=" + id,
success: function(data) {
isUser = ($(data).text().indexOf("Invalid User") == -1);
if (isUser) {
username = $(data).find(".normal").text();
saved = id - invalid;
$.ajax({
type: 'POST',
url: "save.php",
data: {'username': username},
success: function(data) {
$("#test").append(id+" "+data + "<br />");
select.text(sitename+"("+saved+"/"+total+")"); //Updating numbers of fetched profiles on the frontend
}
});
}
else
invalid++; //loop again here because a user wan't valid
progress();
}
});
}
}
for (i = 0; i < members; i++) {
fetched++;
setTimeout(fetchMember(fetched, select, sitename, total), wait*i);
}

基本上我需要做的是如果在操作结束时有一些无效用户,则再次循环,非常感谢任何帮助

最佳答案

我想知道这段代码是否对您有帮助,尽管它没有完全适合您的情况并且没有经过测试。主要原理是memberFetch函数的递归调用。在这种情况下不需要超时 - 它不会向服务器发出任何新请求,直到收到最后一个请求的响应。随意提出任何问题,但请尝试自己尝试:)

var currentId = 0; // Current member id
var membersNum = 10; // There are 10 members from 0 to 9
var neededValidUsersNum = 5; // We need only 5 valid users...
var valudUsersNum = 0; // ... but now we have 0 of them

// Let's make an array of all possible id's
// It will be a queue - we will try to fetch the first id
// In case of success - save data, remove that id from the queue, fetch the nex one
// Otherwise - put it at the back of the queue to try it again later
var possibleIds = [];
for (var i = 0; i < membersNum; i++) {
possibleIds.push(i);
}

// Fetched user data storage
var userData = {};

function fetchMember(id) {
var data = "some data";

$.post('script.php', data)
.done(function(responseData){
onFetchMemberDone(id, responseData);
})
.fail(function(){
onFetchMemberFail(id);
});
}

function onFetchMemberDone(id, responseData){
// Save recieved user data
userData[id] = responseData;
// Bump valid users num
valudUsersNum++;
// If there are not enough valid users - lets continue:
if (valudUsersNum < neededValidUsersNum) {
// Remove valide user from the queue (it was the first one)
possibleIds.shift();
// try to fetch the next one
var nextPossibleId = possibleIds[0];
fetchMember(nextPossibleId);
}
}

function onFetchMemberFail(id){
// add failed user to the end of the queue
possibleIds.push(id);
// try to fetch the next one
var nextPossibleId = possibleIds[0];
fetchMember(nextPossibleId);
}

// Lets launch the cycle! It doesn't look like one because it works through recursive calls
onFetchMember(0);

关于javascript - 需要根据条件再次循环javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25569396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com