createAsyncThunk中过早的承诺实现



所以我在这里有这段代码,它要求第二次调用基于第一次调用返回的参数。所以我把它像这样链接起来。

export const fetchUserInfo = createAsyncThunk(
'fetchUserInfo',
async (param1) =>
axios
.get(process.env.FIRST_CALL, {
params: { code: param1 },
})
.then((firstCallResponse) => {
axios
.get(process.env.SECOND_CALL, {
headers: {
token: firstCallResponse.data.token,
},
})
.then((secondCallResponse) => {
return {
status: LoginStatus.SUCCESS,
payload: { firstCallResponse, secondCallResponse },
}
})
.catch((error) => {
console.log(error)
return { status: LoginStatus.SECONDCALL_FAILURE, payload: {} }
})
})
.catch((error) => {
console.log(error)
return { status: LoginStatus.FIRSTCALL_FAILURE, payload: {} }
}),
)

不幸的是,这个调用触发了extraReducer fetchUserInfo。并在成功完成axios.get(SECOND_CALL)

之前返回一个响应。你如何建立一个承诺链,使它必须等待所有的axios。成功还是失败?

你的第一个API调用的承诺没有与第二个API调用的承诺序列化。因为您没有返回axios.get(SECOND_CALL)创建的承诺。

工作示例:

import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
const LoginStatus = {
SUCCESS: 'SUCCESS',
SECONDCALL_FAILURE: 'SECONDCALL_FAILURE',
FIRSTCALL_FAILURE: 'FIRSTCALL_FAILURE',
};
export const fetchUserInfo = createAsyncThunk('fetchUserInfo', async () =>
axios
.get('https://jsonplaceholder.typicode.com/users/1')
.then((firstCallResponse) => {
return axios
.get('https://jsonplaceholder.typicode.com/users/2')
.then((secondCallResponse) => {
return {
status: LoginStatus.SUCCESS,
payload: { firstCallResponse: firstCallResponse.data, secondCallResponse: secondCallResponse.data },
};
})
.catch((error) => {
return { status: LoginStatus.SECONDCALL_FAILURE, payload: {} };
});
})
.catch((error) => {
console.log(error);
return { status: LoginStatus.FIRSTCALL_FAILURE, payload: {} };
}),
);
const userInfoSlice = createSlice({
name: 'user',
initialState: {},
reducers: {},
extraReducers(builder) {
builder.addCase(fetchUserInfo.fulfilled, (state, action) => {
console.log(action);
return state;
});
},
});
const store = configureStore({ reducer: userInfoSlice.reducer });
store.dispatch(fetchUserInfo());

输出:

{
type: 'fetchUserInfo/fulfilled',
payload: {
status: 'SUCCESS',
payload: { firstCallResponse: [Object], secondCallResponse: [Object] }
},
meta: {
arg: undefined,
requestId: 'l0lJmWjt2BMsVjbJUvVs1',
requestStatus: 'fulfilled'
}
}

相关内容

  • 没有找到相关文章

最新更新