Multiple requests with axios without waiting for all of them to finish in an array list?

假如想象 提交于 2019-12-23 06:01:17

问题


taskList.push(
    const data = {
        url: 'http://${requestUrl}?${argsString}',
        headers: {
            'Content-Type': 'application/octet-stream',
            Authorization: signature //,
            //'Content-Length': buffer.length
        },
        method: 'POST',
        data: buffer
    }
            return axios(data)
        )

try {
        const data = await Promise.all(taskList)
        const res = data.map(d => d.data)
        console.log(res)
        //ctx.state.data = res
    } catch (e) {
        console.log(e)
        throw e
    }

How to do not wait all requests finish, because all finish needs too long time. If any request finish, I print it out, it will be very fast for users.


回答1:


In case each response should be logged as soon as it's completed, it should be:

const responses = await Promise.all(taskList.map(async task => {
  const { data } = await task;
  console.log(data);
  return data;
}));



回答2:


To run each Promise just add a .then() to each of one them or to the Promise.all, however you will not be able to .map the data after:

try {
    const data = Promise.all(taskList).then(() => console.log('finished'));
    // this will not wait to run, so data will be probably undefined
    const res = data.map(d => d.data)
    ...

So I'd suggest following the pattern and waiting for them to finish.

If it's taking too long maybe you should try improve the performance of the response in the back-end if that's possible.



来源:https://stackoverflow.com/questions/53244989/multiple-requests-with-axios-without-waiting-for-all-of-them-to-finish-in-an-arr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!