react redux,thunk fulfilled 事件过早发生

react redux, thunk fulfilled event happens prematurely

我在我的项目的其他区域使用了类似的 Thunk 和 slice,并且都按预期工作,但这个特定的不起作用,这个 Thunk 的不同之处在于它包含一个等待结果的 axios 调用,以便它可以链接到下一个 axios 调用。

登录后我认为问题是 Thunk 在第一次 axios 调用后触发 'fulfilled' 而不是等待完整功能完成,这个问题让我难以解决如何解决这个问题。

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;
        }
    }
});

主要问题是您的函数不会等待 Promise 完成。它也从未 return routeData.

你还用大量的迭代和推来推去的东西弄乱了你的函数。很容易忘记在哪里必须 return 东西。我知道 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])
        )
});