axios 同时多个请求_如何同时发布多个Axios请求?

At this moment I have a webpage in which a long list of Axios POST calls are being made. Now, the requests seem to be sent in parallel (JavaScript continues sending the next request before the result is received).

However, the results seem to be returned one by one, not simultaneously. Let's say one POST call to the PHP script takes 4 seconds and I need to make 10 calls. It would currently take 4 seconds per call, which would be 40 seconds in total. I hope to find a solution to both and receive all results at approximately the same time (~4 seconds) instead of ~40 seconds.

Now I've read about threads, multithreading in NodeJS using Workers. I've read that JavaScript itself is only single-threaded, so it may not allow this by itself.

But I'm not sure where to go from here. All I have are some ideas. I'm not sure whether or not I'm heading into the right direction and if I am, I am not sure how to use Workers in NodeJS and apply it in my code. Which road should I take? Any guidance would be highly appreciated!

Here is a small piece of example code:

for( var i = 0; i < 10; i++ )

{

window.axios.post(`/my-url`, {

myVar: 'myValue'

})

.then((response) => {

// Takes 4 seconds, 4 more seconds, 4 more seconds, etc

// Ideally: Takes 4 seconds, returns in the same ~4 seconds, returns in the same ~4 seconds, etc

console.log( 'Succeeded!' );

})

.catch((error) => {

console.log( 'Error' );

});

// Takes < 1 second, < 1 more second, < 1 more second, etc

console.log( 'Request sent!' );

}

解决方案

There are three cases via you can achieve your goal.

1) For simultaneous requests with Axios, you can use Axios.all()

axios.all([

axios..post(`/my-url`, {

myVar: 'myValue'

}),

axios.post(`/my-url2`, {

myVar: 'myValue'

})

])

.then(axios.spread((data1, data2) => {

// output of req.

console.log('data1', data1, 'data2', data2)

}));

2) you can use Promise.allSettled(). The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected,

3) You can try to use Promise.all() but it has the drawback that if any 1 req failed then it will fail for all and give o/p as an error(or in catch block)

but the best case is the first one.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值