Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this efficiently using Kodar?

 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;
  }
});

Answer №1

When coding in JavaScript, the await keyword plays a crucial role in waiting for promises to be fulfilled before progressing with the code execution. (refer to documentation)

If you find yourself in a situation where you need to handle multiple asynchronous requests without using the await keyword, an alternative approach is to utilize Promise.all. By employing Promise.all, you can streamline your code and efficiently manage multiple requests. (see official documentation)

Incorporating this technique into your code involves restructuring it as follows:

 onMounted(async () => {

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

By using Promise.all in this manner, all specified requests will be executed concurrently, enhancing the efficiency of your code. Notably, error handling becomes more straightforward when leveraging Promise.all, as any rejection within the promises will result in the entire expression throwing an error, as per the documented behavior:

Utilizing Promise.all aligns with best practices, particularly due to its intuitive error handling mechanism—should any promise reject, the overall outcome becomes unavailable, triggering an exception in the await process.

I trust that this explanation proves beneficial for your implementation.

Answer №2

Consider using either Promise.all() or Promise.allSettled() to handle multiple asynchronous requests simultaneously.

An alternative approach with Promise.allSettled() would be as follows:

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);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating with Nokia Here maps: plotting a path using GPS coordinates

I am currently developing a GPS tracking system and my goal is to visually represent the device's locations as a route. The challenge I'm facing is that there is a REST API available for this purpose, but my client-side application relies on soc ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

What is the best way to display a div beneath the highlighted text within a textarea field?

I have encountered a situation where I want to display a div (like a popup) when text is selected in a text area. However, when using mouse-down for this action, the position of the div sometimes does not align directly below the selected text. Below is t ...

Is there a way to confirm if the target has been successfully removed from the element using jQuery?

$(".dropdown-toggle").click(function(event) { var target = $(event.target); if (target.is(this)) { $(this).find(".caret").toggleClass("customcaret"); } }); <div class="dropdown-toggle"> <div class="caret"></div> </div> ...

What steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

I am verifying the user's login status and directing them to the login page if they are not already logged in

My goal is to utilize ionViewWillEnter in order to verify if the user is logged in. If the check returns false, I want to direct them to the login page and then proceed with the initializeapp function. My experience with Angular and Ionic is still limite ...

Can two different versions of a library be utilized simultaneously in NPM?

Currently, our Vue.js app is built with Vuetify v1.5 and we are considering transitioning to Vuetify 2.0. However, the process would involve numerous breaking changes which we currently do not have the resources to address for all components. Is there a wa ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Downloading a zip file using PHP works successfully when initiated directly, but encounters errors when attempted through a web application

I have been working on a PHP script that generates a zip file and allows it to be downloaded from the browser. The download function in the code snippet below: download.php // ensure client receives download if (headers_sent()) { echo 'HTTP head ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked. I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clic ...