我在项目的其他区域中使用了类似的Thunk和slice,并且所有工作都按预期进行,但是这一特定操作不起作用,与Thunk的不同之处在于它包含一个等待结果的axios调用,以便可以将其链接在一起。下一个axios呼叫。
登录后,我认为问题是Thunk在第一个axios调用后触发了“已实现”,而不是等待完整的功能完成,这使我很困惑如何解决此问题。
export const getPlanAPI = createAsyncThunk('dataStorePlans/plan', async () => {
const response = await axios.get('/api/routes')
let promises = [];
const routeData = [];
// I think the Thunk is firing 'fulfilled' at this point.
try {
for (let i = 0; i < response.data.length; i++) {
promises.push(axios.get('/api/routedetail?planid=' + response.data[i].id + '&jobcount=' + response.data[i].jobs))
}
} catch (error) {
console.log(error);
}
Promise.all(promises).then(function (results) {
results.forEach(function (response) {
routeData.push(response.data[0]);
})
return routeData
});
});
export const planSlice = createSlice({
name: 'dataStorePlans/plan',
initialState: {
planList: [],
status: ''
},
reducers: {
getPlanState: (state) => {
return state
}
},
extraReducers: {
[getPlanAPI.pending]: (state, action) => {
state.status = 'Loading';
},
[getPlanAPI.fulfilled]: (state, action) => {
state.status = 'Success';
state.planList = action.payload
},
[getPlanAPI.rejected]: (state, action) => {
state.status = 'failed';
action.error = action.error.message;
}
}
});
主要问题在于您的职能部门不会等待承诺完成。它也从未返回routeData
。
您还会通过大量的迭代和推挤来使函数混乱。很容易忘记您必须在哪里退货。我知道这async
是新的热门话题,但是Promise链在这里效果更好。即使我保留了您的结构,但如果map
在正确的位置使用它,该函数也将变得更易于阅读。
export const getPlanAPI = createAsyncThunk('dataStorePlans/plan', async () => {
const response = await axios.get('/api/routes')
let promises = [];
try {
promises = response.data.map(({id, jobs}) =>
axios.get(`/api/routedetail?planid=${ id }&jobcount=${ jobs }`)
)
} catch (error) {
console.log(error);
}
return Promise
.all(promises)
.then(results =>
results.map(response => response.data[0])
)
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句