Maks
Maks

Reputation: 97

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

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?

Upvotes: 1

Views: 246

Answers (1)

Moritz Ringler
Moritz Ringler

Reputation: 15931

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.

Upvotes: 1

Related Questions