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

Creating multiple tabs in PHP using the header function can be achieved by specifying the location in

I am attempting to open a new tab using Php code: header("location:print_register.php?recpt_no=".$recpt_no); In addition, I would like to open two tabs programmatically with the following code snippet: header("location:print_register.php?recpt_no=".$rec ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

Ways to determine the presence of a value in an array

Here is an example array: [ {practitioner: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false}, {practitioner: "place_1509136116772", H0709: true, H0911: false, H1113: true, H1315: false}, {practitioner: "place_15091361166 ...

Using jQuery, is there a way to move an element from one div to another, but only if the destination div is currently empty

<div id="apply"></div> <div id="droppable_slots"> <div class="slot 1">1</div> <div class="slot 2">2</div> <div class="slot 3">3</div> </div> Is there a way to utilize jquery in order ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

Interactive loading of datalist choices using AJAX in the Firefox browser

I have recently decided to replace the Jquery UI autocomplete function on my website with HTML5 datalists that load dynamic options. After researching this topic extensively, I came across various answers on Stack Overflow, such as How do you refresh an HT ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

Using Vue 2 with a personalized Axios setup, integrating Vuex, and incorporating Typescript for a robust

I'm still getting the hang of Typescript, but I'm facing some challenges with it when using Vuex/Axios. Current setup includes: Vue CLI app, Vue 2, Vuex 3, Axios, Typescript At a high level, I have a custom Axios instance where I configure the ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

How do I modify the local settings of the ngx-admin datepicker component to show a Turkish calendar view?

Looking for tips on customizing the new datepicker component in Nebular ngx-admin. Specifically, I want to change the local settings to display the calendar as Turkish. Explored the library but still seeking alternative methods. Any suggestions? ...

JavaScript - Retrieve the name of an object from a separate array

Is it possible to dynamically map rows and columns in a table component using arrays of objects? For example, I have two arrays of objects like this: const columnData = [ { id: 'name', label: 'Name' }, { id: 'value', lab ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

Checking for the presence of text within a span tag - a simple guide

see fiddle if there is an already allotted time slot for the patient, change its color to yellow using jquery on the client side. In my example, if I assign a time slot for the first time, it turns green and when assigning another one, the previous slot tu ...

Add a fresh record only if it contains information and there are no existing duplicates present

Is it possible to create a note with both a title and text, under certain conditions? The title must not be empty The title cannot already exist in the system When attempting to check for duplicates within my array, the boolean value always returns true ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Issue encountered during installation of react-masonry-css using npm

PS E:\Share me\shareme_frontend\my-project> npm install react-masonry-css npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...