there is something I want to do. I need to send requests to 4 different places in the onmounted function in the composition api, but I want to send requests to all of them with promise at the same time, how can I do this with this kodar for performance
onMounted(async () => {
const [error, res] = await ExApiService.get("exit-city");
if (error) ErrorPopup(error);
else {
exitCityId.value = res.data;
}
const [err, resp] = await ExApiService.get("destination-city");
if (err) ErrorPopup(err);
else {
destinationCityId.value = resp.data;
}
const [er, re] = await ExApiService.get("destination-warehouse");
if (er) ErrorPopup(er);
else {
destinationWarehouseId.value = re.data;
}
const [e, r] = await ExApiService.get("expense-detail");
if (e) ErrorPopup(e);
else {
expenseDetail.value = r.data;
}
});
2
Answers
Use
Promise.all()
orPromise.allSettled()
, those let you wait for a number of concurrent async requests.With
Promise.allSettled()
, your example would look something like this:the
await
key is used to await for a promise to be fulfilled before continuing with the rest of the code. (see docs)So, one way to do it is by removing the
await
key from the requests.But since you are working with the response, I would suggest using
Promise.all
(docs)Your code should be something like this:
Using
Promise.all
with execute all the requests listed as parameters and wait for all of them to be fulfilled. And since you are handling the error the same way for all of them and as mentioned in the docs:I hope this helps