ReactJs 异步函数问题

问题描述 投票:0回答:1

我有一个名为 login.js 的切片文件,并且我使用 createAsyncThunk 在 login.js 文件内分派一个函数。当我调用 createAsyncThunk 函数内的类时,它不会等待响应。我哪里做错了?

login.js代码(切片文件)

export const login = createAsyncThunk("login", async (oParams, thunkAPI) => {
    try {
        await AuthService.login(oParams, (response) => {
            return response;
        });
    } catch (e) {
        return thunkAPI.rejectWithValue(e.response || e);
    }
});

auth.service.js 文件代码

import RequestProvider from '../provider/service.provider';

const login = async (payload, callback) => {
    //RequestProvider is a Class which contains parameters and sending request inside.
    new RequestProvider("POST", "login", "api_name", "companyId=100", payload, 
    (oResponse) => {
        callback(oResponse);
    });
};

const AuthService = {
    login
};

export default AuthService;

service.provider.js 代码;

import { loginAxiosConfig } from "../../../../axiosConfig";

export default class RequestProvider {
    constructor(requestType, methodName, apiName, requestQueryParams, requestPayload, 
    callback) {
        this.requestType = requestType;
        this.methodName = methodName;
        this.apiName = apiName;
        this.requestQueryParams = requestQueryParams;
        this.requestPayload = requestPayload;
        this.callback = callback;

        if (requestType === "POST") {
            this.postRequest();
        }

        if (requestType === "GET") {
            this.getRequest();
        }
    }

    postRequest() {
        if (this.methodName === "login") {
            loginAxiosConfig.post(`/${this.apiName}/${this.methodName}? 
            ${this.requestQueryParams}`, this.requestPayload).then((response) => {
                this.callback(response);
            }).catch(() => {
                this.callback(false);
            });
        } else {

        }
    }

    getRequest() {
        return this.requestType;
    }

}
javascript reactjs redux async-await redux-toolkit
1个回答
0
投票

AuthService.login
函数调用包装在 Promise 回调中,并将
resolve
函数作为回调传递给
AuthService.login

export const login = createAsyncThunk(
  "login",
  async (oParams, thunkAPI) => {
    try {
      const response = await new Promise(resolve => {
        AuthService.login(oParams, resolve);
      });
      return response;
    } catch (e) {
      return thunkAPI.rejectWithValue(e.response || e);
    }
  }
);
const login = async (payload, callback) => { // <-- callback is resolve
  // RequestProvider is a Class which contains parameters and sending request inside.
  new RequestProvider(
    "POST",
    "login",
    "api_name",
    "companyId=100",
    payload, 
    (oResponse) => {
      callback(oResponse); // <-- passes oResponse to resolve
    }
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.