如何在Vue 3中同时发送多个异步请求,使用``。

huangapple go评论55阅读模式
英文:

How to send several async requests at the same time using suspense vue 3

问题

我使用<Suspense>,在我的子组件中有几个请求,使用await:

await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res);
await store.dispatch("product/getCharacteristics", route.params.id).then(res => characteristicList.value = res);
await store.dispatch("price/getPrices", route.params.id).then(res => delivery.value = res);

所以它们一个接一个地运行,但我需要它们同时运行。

我的解决方案:我用const request = ...替代了await

现在我只有一个await:

await Promise.all([request1, request2, request3, request4, request5, request6, request7]);

这是一个好的做法吗?还是有更好和更优雅的方法?

英文:

I'm using &lt;Suspense&gt; and I have several requests in my child component with await:

await store.dispatch(&quot;product/getProduct&quot;, route.params.id).then(res =&gt; productData.value = res);
await store.dispatch(&quot;product/getCharacteristics&quot;, route.params.id).then(res =&gt; characteristicList.value = res);
await store.dispatch(&quot;price/getPrices&quot;, route.params.id).then(res =&gt; delivery.value = res);

So they run one by one, but I need them to run at the same time

My solution: I replaced await with const request = ...

And now I have only one await:

await Promise.all([request1, request2, request3, request4, request5, request6, request7]);

Is it good practice? Or is there a better and more elegant way to do this?

答案1

得分: 1

是的,这就是Promise.all()的用途,而且这是非常好的实践。应该尽可能使用它以降低等待时间。

有些人(不包括我)通常更喜欢Promise.allSettled()。它在内部 promise 失败时不会拒绝,这允许更精细的错误处理,但你必须解包返回的对象。

英文:

Yes, this is what Promise.all() is for and it is very good practice. You should use it whenever possible to keep wait time low.

Some people (who are not me) generally prefer Promise.allSettled(). It does not reject when one of the inner promises fails, which allows for more refined error handling, but you have to unwrap the returned objects.

huangapple
  • 本文由 发表于 2023年2月6日 21:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定