我有一些赛蜜蜂。在我的redux商店中,它们是具有name属性和可能性属性的数组中的对象。对于每只蜜蜂,我想计算一下获胜的可能性。计算算法是异步的。当我开始计算所有蜜蜂时,蜜蜂的似然属性应该具有“计算”值,当蜜蜂的计算完成时,似然属性应该显示一个数字。
我有一个无法修改的函数generateBeeWinLikelihoodCalculator
。
现在,我的代码并没有单独计算为蜜蜂获胜的可能性,而我对如何最好地实现这一目标感到茫然。我想到将calcultingLikelihood函数调度到每个bee实例并在reducer中调用它,但是如何让它首先返回'calculate ...'然后当setTimeout运行时,然后返回值?
let state = {bees:[{name: 'marie'},{name: 'john'}]}
const reducer = (state, action) => {
switch (action.type) {
case 'FETCH_BEES':
return {
...state,
bees: action.bees,
}
case 'RUN_CALCULATIONS':
return {
...state,
bees: state.bees.map(bee => {
bee.likelihood = action.likelihood
return bee
})
}
case 'DISPLAY_CALCULATIONS':
return {
...state,
bees: state.bees.map(bee => {
bee.likelihood = action.likelihood
return bee
})
}
default: return state
}
}
const runCalculations = (likelihood) => ({
type: 'RUN_CALCULATIONS',
likelihood,
})
const displayCalculations = (likelihood) => ({
type: 'DISPLAY_CALCULATIONS',
likelihood,
})
const store = {
dispatch: (action) => {
state = reducer(state,action)
return state
},
getState: () => {
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()))
const callback = (likelihoodOfBeeWinning) => {
store.dispatch(displayCalculations(likelihoodOfBeeWinning))
console.log(JSON.stringify(store.getState()))
}
return generateBeeWinLikelihoodCalculator()(callback)
}
calculatingLikelihood()
答案 0 :(得分:1)
我也会给蜜蜂一个id属性,并将它们作为蜜蜂的地图存储,通过id和蜜蜂阵列。这样可以更轻松地更新州内的个别蜜蜂。
您也可以使用promises或async / await。
状态变为:
let state = {bees:{1:{id:1,name:'marie'},2:{id:2 name:'john'}}
// Grab the list of Bees
const bees = store.getState().bees
// Work on each bee and update it individually
Object.values(bees).forEach(async bee => {
const likelihood = await calculate(bee)
store.dispatch({ type: 'UPDATE_BEE', payload: { ...bee, likelihood } })
})
// Or you could wait for all calculations to resolve before updating state
const promises = Object.values(bees).map(async bee => {
const likelihood = await calculate(bee)
return { ...bee, likelihood }
})
Promise.all(promises).then(bees => {
store.dispatch({ type: 'UPDATE_BEES', payload: _.keyBy(bees, 'id') })
})