Utilizing a promise array in conjunction with v-data-table

In my custom table component, I am using a v-data-table to display data that is passed as a prop. I perform some data cleaning operations and then call an asynchronous function to fetch additional data from an API:

//load cloud storage data
const cleanData = ref<any[]>()

const loadThumbnails = async (dmcp_tab_id : number, dmcp_box_id : string) => {
  let attempts : number = 1
  const result = ref<CloudStorage | null>()
  do {
      attempts=attempts+1
      result.value = await documentStore.getCloudStorage(dmcp_tab_id, dmcp_box_id)
    } while (result.value!.thumbnail == "" && attempts <= 5)
  
  return result.value?.thumbnail
}

const loadCloudStorageData = () => {
  cleanData.value = props.data
  cleanData.value = props.data.map(async (item) => { return {...item, when_uploaded: dayjs(item.when_uploaded).format('MM/DD/YYYY'), thumbnail: await loadThumbnails(item.dmcp_tab_id, item.dmcp_box_id)}})
}

loadCloudStorageData()
watch(props.data, () => {
  loadCloudStorageData()
})

Upon inspecting the cleanData and using console.log(), I noticed that it resolves to an array of promises, resulting in nothing being displayed in the v-data-table. However, if I remove the await and async from the thumbnail function, everything loads correctly into the v-data-table. I am uncertain how to handle promises within the v-data-table.

Answer №1

Dealing with an array of promises is a common task, not specific to Vue. To handle this scenario, we make use of the Promise.all method.

// This helper function imitates data fetching from an API asynchronously
async function fetchDataFromApi(data, delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data);
    }, delay);
  });
}

async function fetchAllData() {
  try {
  
    const promises = [
      fetchDataFromApi({ name: 'Bill' } , 500),
      fetchDataFromApi({ name: 'Ted' }, 0),
      fetchDataFromApi({ name: 'Rufus' }, 200),
    ];

    console.log('before Promise.all', promises)

    const results = await Promise.all(promises);
    
    console.log('after Promise.all', results);
 
  } 
  catch (error) {
    console.error('Oops', error);
  }
}

fetchAllData();

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

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

WebRTC functions effectively within the same network, but encounters difficulty when communicating between different IP addresses

Please find my code on Github: https://github.com/rashadrussell/webrtc_experiment/blob/master/public/script.js I am currently working on developing a 1-to-1 video conferencing script using WebRTC. The script is hosted on AppFog, a cloud hosting platform. ...

Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience. For instance, the polyfill fitie b ...

Picking and modifying a newly added HTML input element using Jquery

I am encountering a problem that I haven't been able to find a solution for through research or Google. I managed to successfully add multiple input boxes to my HTML/JQuery project, which are displaying correctly on the webpage. for (i = 0; i < ma ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...

What is the process for turning off a TypeScript rule for a single line of code?

Dealing with Summernote as a jQuery plugin has been a bit of a struggle for me. I'm trying to modify the object without needing type definitions, but TypeScript keeps throwing errors my way. Even after attempting to delete certain keys, I still get th ...

Protractor sendKeys method on Modal dialog is failing due to element visibility issues

I seem to be facing a strange issue with protractor. My challenge lies in testing a form that is situated within a modal. Although I am able to verify that the modal is indeed open, I encounter difficulties when attempting to sendKeys to the input fields. ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

The RGB values of a dynamically loaded image being drawn to a canvas in JavaScript are slightly off

After hosting some .PNG images on my NGINX webserver, I noticed a discrepancy in the RGB values when loading and drawing them on a canvas using context.drawImage(img, 0, 0); and retrieving the image data using context.getImageData(x, y, 1, 1).data. Interes ...

Tips for implementing a single function across multiple HTML classes using JavaScript

For the past few days, I've been struggling with a JavaScript issue as a newcomer to the language. $(document).on('click', '.content-click', function(){ $(".content-click span").toggleClass("clicked"), $(".content-view") ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

Tips on utilizing the enter key to add my <li> element to the list?

Currently, my to-do list setup requires users to click a button in order to add a new list item. I am looking to enhance the user experience by allowing them to simply hit "enter" on their keyboard to achieve the same result. Here is the JavaScript code I ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Using Webpack to directly embed image paths in your code

I am working on a project that uses webpack and vue.js. I encountered an issue when trying to add an image to the vue template using src '/images/imageName.png', which resulted in a 404 error. How can I adjust the configuration to recognize absol ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

Display all keys and values in a dynamically populated object on my screen - React

I have a dynamic object with nested objects, and I want to display every key and value. Even if there are objects within the main object, I need to show their keys and values as well. Here is an example of the object: info:{ address:{ city: {__o ...

Guide to accessing object items in v-for in VueJs

Upon inspection, the following results are being displayed: https://i.sstatic.net/oF4Qe.png https://i.sstatic.net/21aHB.png In the Vue template code provided: <select class="form-select" v-model="post_format.wpml_language"> <option v-for="(l ...