gpt4 book ai didi

Javascript forEach - 在迭代之前等待 setTimeout 完成

转载 作者:行者123 更新时间:2023-12-01 03:43:16 25 4
gpt4 key购买 nike

我有以下内容:

https://jsfiddle.net/qofbvuvs/

var allItems = ["1", "2", "3"]
var allPeople = ["A", "B"]

var testFoo = function(itemValue, peopleValue) {
setTimeout(function(){
return itemValue == "3" && peopleValue == "B"
}, 200)
}

allItems.forEach(function(itemValue) {
allPeople.forEach(function(peopleValue) {
// I want to iterate through each object, completing testFoo before moving on to the next object, without recursion. TestFoo has a few instances of setTimeout. I've tried using promises to no avail.
if (testFoo(itemValue, peopleValue)){
alert("success")
} else{
// nothing
};
})
})
alert("complete")

我的目标是按顺序逐项迭代每个项目,同时等待 testFoo 的结果。如果 testFoo 通过,那么我应该停止执行。

我尝试使用 promise ( https://jsfiddle.net/qofbvuvs/2/ ),但无法获得我正在寻找的行为。 Success 应在 Complete 之前调用。 TestFoo 有几个我需要解决的 setTimeouts(这是一个我无法修改的库)。如何实现这一目标?

最佳答案

实现此目的的一种方法是通过 jQuery 延迟并手动单步执行数组,而不是使用内置循环,这样您就可以控制是否/何时继续。我猜它在某种程度上使用了递归,但无非是为了调用下一次迭代 - 没有疯狂的递归返回值解析或任何使递归变得复杂的东西。让我知道这是否适合您:

var allItems = ["1", "2", "3"]
var allPeople = ["A", "B"]

var testFoo = function(itemValue, peopleValue) {
var deferredObject = $.Deferred();
setTimeout(function() {
deferredObject.resolve(itemValue == "3" && peopleValue == "B")
}, 200)
return deferredObject;
}
var currentItemIndex = 0;
var currentPeopleIndex = 0;

var testDeferred = $.Deferred();

function testAll() {
testFoo(allItems[currentItemIndex], allPeople[currentPeopleIndex]).done(function(result) {
if (result) {
// found result - stop execution
testDeferred.resolve("success");
} else {
currentPeopleIndex++;
if (currentPeopleIndex >= allPeople.length) {
currentPeopleIndex = 0;
currentItemIndex++;
}
if (currentItemIndex >= allItems.length) {
// result not found - stop execution
testDeferred.resolve("fail");
} else {
// check next value pair
testAll();
}
}
});
return testDeferred;
}

testAll().done(function resolveCallback (message) {
alert(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于Javascript forEach - 在迭代之前等待 setTimeout 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726533/

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