同时运行多个axios请求,只向后端产生一个请求

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

是否可以同时运行多个axios请求,并且只向后端产生一个请求?

这是我试图在拦截器中执行的操作,但我被卡住了:

instance.interceptors.request.use((request: AxiosRequestConfig) => {
        return new Promise((resolve, reject) => {
            if (timeout) {
                clearTimeout(timeout);
            }

            let ids: any[] = [];
            temp_id = [...temp_id, request.params];
            queue = [...queue, request];

            timeout = setTimeout(async () => {
                const output = await temp_id.map(e => e['ids'])
                await output.map(r => {
                    ids = Array.from(new Set(ids.concat(r)));
                });

                const config: AxiosRequestConfig = {
                    ...request,
                    baseURL: request.baseURL,
                    headers: request.headers,
                    params: { ids }
                };

                resolve(config);
            }, 1000);
        })
        // return request;
    }, (err) => Promise.reject(err))

期望:

假设我们发出了这 2 个请求,我想拦截该请求,合并参数并使用新参数向服务器发送一个请求。

const uri = "/uri";
    let a = api.get(uri, {params: { ids: [0,1,2] }});
    let b = api.get(uri, {params: { ids: [2,3] }});
    return Promise.all([a, b])
        .then(e => console.log(e))
        .catch(err => console.log(err.response))

输出:

在拦截器中,我应该能够过滤参数并向服务器发送单个请求:

   const output = await temp_id.map(e => e['ids'])
   await output.map(r => {
       ids = Array.from(new Set(ids.concat(r)));
   });

   //send out a single request with params { ids: [0,1,2,3] }
javascript react-native axios
1个回答
0
投票

我通过消除发出 api 请求的函数来修复此问题。查找下面的示例:

const oldData = [1, 2, 3]
const funcMakingApiRequest = _debounce(
   (currData) => {
     const payload = [...oldData, ...currData]
     // make axios request with payload after debounce
   },
   500,
   {
     leading: true,
     trailing: false,
   }
 )
© www.soinside.com 2019 - 2024. All rights reserved.