일부 경주 용 꿀벌이 있습니다. 내 redux 저장소에서는 name 속성과 likelihood 속성이있는 배열의 개체입니다. 각 벌에 대해서, 나는 그 우승 확률을 계산하고 싶습니다. 계산 알고리즘은 비동기입니다. 모든 꿀벌의 계산을 시작할 때 꿀벌의 우도 속성은 '계산'값을 가져야하며, 꿀벌 계산이 완료되면 우도 속성은 숫자를 표시해야합니다.Redux 저장소의 항목에 대해 별도의 비동기 호출 처리
수정 할 수없는 기능이 generateBeeWinLikelihoodCalculator
입니다.
지금 당장은 꿀벌을 따로 뽑을 확률을 계산하지 않아이를 달성하는 최선의 방법을 찾지 못했습니다. 각 꿀벌 인스턴스에 calcultingLikelihood 함수를 보내고 감속기에서 호출하는 방법을 생각해 보았습니다. 그렇다면 먼저 '계산 중 ...'을 반환하고 setTimeout이 실행되면 값을 반환해야합니다.
let state = {bees:[{name: 'marie'},{name: 'john'}]}
const reducer = (state, action) => {
\t switch (action.type) {
\t case 'FETCH_BEES':
\t return {
\t ...state,
bees: action.bees,
}
case 'RUN_CALCULATIONS':
\t return {
\t ...state,
bees: state.bees.map(bee => {
\t bee.likelihood = action.likelihood
return bee
})
}
case 'DISPLAY_CALCULATIONS':
\t return {
\t ...state,
bees: state.bees.map(bee => {
\t bee.likelihood = action.likelihood
return bee
})
}
default: return state
}
}
const runCalculations = (likelihood) => ({
\t type: 'RUN_CALCULATIONS',
likelihood,
})
const displayCalculations = (likelihood) => ({
\t type: 'DISPLAY_CALCULATIONS',
likelihood,
})
const store = {
\t dispatch: (action) => {
\t state = reducer(state,action)
\t return state
},
getState:() => {
\t return state
}
}
//this calculator cannot be modified
const generateBeeWinLikelihoodCalculator =() => {
var delay = 1000 + Math.random() * 1000;
var likelihoodOfAntWinning = Math.random();
return function(callback) {
setTimeout(function() {
callback(likelihoodOfAntWinning)
}, delay);
};
}
const calculatingLikelihood =() => {
store.dispatch(runCalculations('calculating...'))
console.log(JSON.stringify(store.getState()))
\t const callback = (likelihoodOfBeeWinning) => {
\t store.dispatch(displayCalculations(likelihoodOfBeeWinning))
\t console.log(JSON.stringify(store.getState()))
}
return generateBeeWinLikelihoodCalculator()(callback)
}
calculatingLikelihood()
내가 틀렸다면 나를 바로 잡습니다 : 당신은 물건의 목록을 가지고 있습니다. 각각의 개별 객체 (꿀벌)을 사용하면 작업이 해결되면 비동기 작업을 수행하고 해당 객체를 상태로 업데이트해야합니다. 상태를 업데이트하기 전에 해결할 모든 작업 약속을 기다리거나 해결 된 각 계산에 대해 상태를 개별적으로 업데이트 할 수 있습니다. – chautelly
해결 된 각 계산의 상태를 업데이트해야하지만 현재 계산을 개별적으로 수행하는 방법에 대한 손실이 있습니다. ... –