skip to Main Content

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


  1. Use Promise.all() or Promise.allSettled(), those let you wait for a number of concurrent async requests.

    With Promise.allSettled(), your example would look something like this:

    onMounted(async() => {
      const promises = [
        ExApiService.get("exit-city"),
        ExApiService.get("destination-city"),
        ExApiService.get("destination-warehouse"),
        ExApiService.get("expense-detail"),
      ];
      const settleds = await Promise.allSettled(promises);
      const errors = settled.filter(sp => sp.status === "rejected");
      errors.forEach(sp => ErrorPopup(sp.reason));
     
      [
        exitCityId.value, 
        destinationCityId.value, 
        destinationWarehouseId.value, 
        expenseDetail.value
      ] = settleds.map(ps => ps.value?.data);
    });
    
    Login or Signup to reply.
  2. 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:

     onMounted(async () => {
    
      const fulfilled = await Promise.all([
            ExApiService.get("exit-city"),
            ExApiService.get("destination-city"),
            ExApiService.get("destination-warehouse"),
            ExApiService.get("expense-detail")
        ]);
        
      });
    

    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:

    Promise.all is the best choice of concurrency method here, because error handling is intuitive — if any of the promises reject, the result is no longer available, so the whole await expression throws

    I hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search