[英]How do i prevent endless loop in while loop in action creator?
Trying to implement some kind of game loop, that will run until conditions are met. 尝试实施某种游戏循环,直到满足条件为止。
However during testing I just can't solve the problem of while loop not waiting for resolve of promises, instead it just calls them over and over again causuing browser to crash. 但是在测试过程中,我只是无法解决while循环问题,而不是等待promise的解决,而是一遍又一遍地调用它们,导致浏览器崩溃。
The combatStart() is called when component is mounted 挂载组件时会调用战斗开始()
export const combatStart = () => {
return function (dispatch, getState) {
while (getState().mechanics.noOfEnemiesAttacked < 5) {
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 3000);
})
setTimeoutPromise.then((resp) => {
if(resp){
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
})
}
}
}
When i dispatch the action the "noOfEnemiesAttacked" increments, and when it reaches 5 the loop should stop. 当我分派动作时,“ noOfEnemiesAttacked”会增加,并且当达到5时,循环应停止。 So it should last around 15 seconds.
因此它应该持续约15秒。
The code works until I add the while loop, otherwise it works as expected, increments the value after 3 seconds when component is mounted. 该代码将一直工作到我添加while循环为止,否则它将按预期工作,在安装组件3秒钟后将值递增。
How can I make this work? 我该如何进行这项工作?
Recursively doesnt work, it doesnt loop, just goes once: 递归不起作用,它不循环,仅执行一次:
export const combatStart = () => {
return function (dispatch, getState) {
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 2000);
})
setTimeoutPromise.then((resp) => {
if (resp) {
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
if (getState().mechanics.noOfEnemiesAttacked < 5) {
console.log(getState().mechanics.noOfEnemiesAttacked)
combatStart();
}
})
}
}
Wrapped it in a function, now it should work 将它包装在一个函数中,现在应该可以工作了
export const combatStart = () => {
return function (dispatch, getState) {
function foo(){
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 2000);
})
setTimeoutPromise.then((resp) => {
if (resp) {
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
if (getState().mechanics.noOfEnemiesAttacked < 5) {
console.log(getState().mechanics.noOfEnemiesAttacked)
combatStart();
foo();
}
})
}
foo();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.