英文:
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 <Suspense>
and I have several requests in my child component with 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);
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论