Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
Extracting value from a DataTransferItem synchronously - what am I doing (wrong) here?

I have a handler function for the drop event which looks somehow like this:

da.addEventListener("drop", function(e) {
    e.stopPropagation();
    var xhr = new XMLHttpRequest();
    ... (configure XMLHttpRequest) 
    var fd = new FormData();
    [...e.dataTransfer.items].forEach(it => {
      it.getAsString(value => {
        console.log(`append ${it.type} ${value}`);
        fd.append(`${it.type}`, value);
      });
    });
    console.log("send");
    xhr.send(fd);
});

The problem here is that send() happens before fd.append(), because it.getAsString() seems to be asynchronous.

After reading some articles about callbacks, asynchronous functions, promises etc. I tried to do the actual appending in a .then() block:

it.getAsString(value => {
  return value;
}).then(value => {
  console.log(`append ${it.type} ${value}`);
  fd.append(`${it.type}`, value);
});

I expected to get into trouble with value not being propagated properly but instead I got

Uncaught TypeError: it.getAsString(...) is undefined

And even the integrated debugger underlines getAsString.

What am I doing here? Why seems getAsString to be defined when I use it without appending .then(value => {}) but works properly without .then()?

On a more abstract level - how would I correctly add items from a DataTransferItem to a FormData instance before sending it?

Update

Combining iterating through .items and then using .getData() works for me but it doesn't feel right..

[...e.dataTransfer.items].forEach(it => {
  fd.append(`${it.type}`, e.dataTransfer.getData(it.type));
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!