处理单独的async要求在Redux Store中使用物品



我有一些赛车蜜蜂。在我的Redux商店中,它们是具有名称属性和可能性属性的数组中的对象。对于每只蜜蜂,我想计算其获胜的可能性。计算算法是异步。当我启动所有蜜蜂的计算时,蜜蜂的可能性属性应具有"计算"的值,当蜜蜂的计算完成时,可能性属性应显示一个数字。

我有一个无法修改的函数generateBeeWinLikelihoodCalculator

现在,我的代码无法分别计算出蜜蜂获胜的可能性,而我为如何最好地实现这一目标而感到不知所措。我想到将Calcultinglikelihood函数派遣到每个Bee实例并在还原器中调用,但是如何将其返回"计算...",然后当Settimeout运行时,然后返回值?p>

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()

我也会给蜜蜂一个id属性,并将它们作为蜜蜂的地图存储为iD与蜜蜂数组。这使得在状态下更新单个蜜蜂。

您也可以使用诺言或异步/等待。

因此状态变为:

让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') })
})

最新更新