Using async and await with promises in the Vue Composition API is the right approach, however, it should not be

I am trying to generate a preview blob from a multi-file input object called "files". I have the previews object set up correctly, but when I use files.value.map, it is not working as expected. My goal is to attach the blob to the "files" object. Can you help me figure out what I am missing?

const files = ref([])
const previews = ref([])

const toBlob = async(file) => {
  const buffer = await file.arrayBuffer()
  const blob = new Blob([buffer])
  const srcBlob = URL.createObjectURL(blob)

  return srcBlob
}

watch(files, async() => {
  previews.value = await Promise.all(
    files.value.map((file) => toBlob(file))
  )

  await Promise.all(files.value.map(async(file) => {
     console.log(file)
     file.preview = await toBlob(file)
  }))
})

 return {
   files,
   previews
 }

The vue template is displaying blank currently. The console log shows the correct information though.

<span v-for="file in files" :key="file">{{file.preview}}</span>

The following code is functioning properly and showing the preview blob:

<span v-for="preview in previews" :key="preview">{{preview}}</span>

Answer №1

When you pass an async function to files.value.map, you receive an array of Promises. It's important to note that you cannot directly await this array, as you can only await a single Promise.

Instead, you can utilize Promise.all to convert an array of Promises into a single Promise:

  await Promise.all(files.value.map(async(file) => {
    console.log(file)
    file.preview = await toBlob(file)
  }))

Answer №3

There's no need to include a .preview property in the File object as they are already stored in previews[]. Simply remove that section of code:

watch(files, async() => {
  previews.value = await Promise.all(
    files.value.map((file) => toBlob(file))
  )

  // xxx: remove
  //await Promise.all(files.value.map(async(file) => {
  //   console.log(file)
  //   file.preview = await toBlob(file)
  //}))
})

When using string interpolation between curly braces, the object URLs will not be displayed as images. Instead, {{previewObjectUrl}} will only show the URL as a string.

To properly render the blobs as images, you must bind the object URLs to an <img>.src:

<img v-for="preview in previews" :key="preview" :src="preview">

Check out the demo here

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

How can one choose the current element in jQuery.Treeview following a jQuery.load(html) event?

Within my HTML code in the sample.html file, I have the following structure: <ul id='topics' class='filetree'> <li><span class='folder'><a href='?Lang=en&TopicID=#'>Topics</a></s ...

Using Typescript to handle the return value of asynchronous functions

In the TypeScript function below, I am encountering an issue: CheckRegUser(u: User): boolean { let b: boolean = true; let toSend = { email: u.email }; this.http.post("http://localhost:8080/", toSend).subscribe((data: Valid) => { ...

Troubleshooting a problem with C3.js charts when utilizing an array

When using c3.js to build a stacked bar chart, I am able to achieve the desired results with static data. However, I run into trouble when attempting to utilize dynamic data. There are two fiddles provided: one showcasing the successful use of static data ...

Various methods for animating a div to slide off the screen

Lately, I've been experimenting with hiding and revealing elements on the edges of my web pages using the following code: $('#myDiv').animate({ width: 'toggle' }, 1000); It works quite well and smoothly slides the div off the pag ...

Setting the value of a CSS property to .value

Currently, I am engrossed in a small project. Here's the gist: I aim to read text field values and assign them to corresponding CSS rules. For example, document.getElementById("BD").value; The value being read should be assigned to border-radi ...

What could be the reason for the full name not being updated in the model when the last name is changed

Can you explain why the full name in the model does not update when I change the last name? You can view the code on Plunker: http://plnkr.co/edit/cqmwJc5dpoDWvai4xeNX?p=preview var loginCntrl=function($scope){ $scope.testClick =function(){ $scope. ...

Guide to setting up a backend system using AJAX, PHP, and MySQL to handle dynamic video sources in conjunction with Google TV Templates

If you're looking to develop web apps for Google TV, particularly those involving video content, the simplest method is to utilize Google TV Templates: https://developers.google.com/tv/web/docs/gtv-templates. The original Google TV Templates included ...

Unable to consolidate subdocument's collection

Having the following documents: I am facing a challenge where I need to aggregate the latest rating from the last array element and then calculate the average of (3,1,3,1). Currently, I am struggling with double unwind and unable to obtain the desired res ...

Is there a way to conceal the parent div when all of its child divs are hidden?

I have a series of dynamically created divs set up like this: <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> < ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

It is impossible to remove or trim line endings with regex in Node.JS

I'm having trouble with using process and util in a NodeJS script. Even after trimming, line breaks persist in the resulting string (as seen in the console.log() output below). I'm unsure why this is happening. var util = require("util"); proces ...

Retrieve the ID value of the paragraph that was clicked on using the right-click function

If I have text with this specific html markup: <p id="myId">Some text <span>some other text</span></p> Is there a way to retrieve the value of the id upon right-clicking on any part of the paragraph? Update: I'm simply pass ...

Google Cloud Functions do not allow initialization of functions at runtime

I am encountering an issue while deploying a basic function on Google Cloud Functions. The error message I am receiving states: Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Here is th ...

Sending JSON data containing an IFormFile and a string as parameters to C#

Software Versions: ASP.NET and Web Tools - 17.10.341.11210 C# Tools - 4.10.0-3.24312.19+ JQuery - 3.3.1.js JS - 2.8.3.js Currently, I am attempting to pass an IFormFile and a string from a JSON file select and a string input. After thorough testing, I ha ...

Arrow Buttons for Expanding and Collapsing Sections on an

I'm attempting to include a downward arrow when the section is closed and an upper arrow when it's open - at the right side of each tab's head in the accordion. Here is the HTML I have implemented. It contains for-each loops. -- JavaScri ...

Organizing React State Arrays

I am struggling to organize an array of objects stored in a React hook state. After sorting, this array is passed to a FlatList component. const { notifications } = useContext(MainContext); const [sortedNotifications, setSortedNotifications] = useState([]) ...

Troubleshooting PhantomJS hanging with WebdriverJS tests on Windows

I am currently using webdriverjs to run automated tests on a Windows 8 system. The tests run successfully when the browser is set to Chrome, but encounter issues when I switch to PhantomJS. Interestingly, the same tests run smoothly on OS X Mavericks. Ins ...

The presence of an undefined variable in `esm.js` is resulting in an overwhelming amount of

After upgrading from Node v14 to Node v16, I encountered a strange error specifically when running node with node -r esm. The error message reads: ReferenceError: myVar is not defined This results in an extensive output of the esm.js module spanning 5000 ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

struggling to transfer information from JavaScript to Jade within the Node.js environment

Currently, I am retrieving a row from a Cassandra table called "emp". My objective is to pass the data retrieved from the JavaScript file to a Jade file in order to display this information on the user interface. In my JavaScript function: router.get(&a ...