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

163
Views
Reading Promise result variable

I am reading the file data as datastring along with filename

My code will result in correct filename but the filedata is displayed empty {}

The expected output is

[{
    filename: "name1.txt",
    filedata: "data:text/plain;base64,VGhpc.."
}, {
    filename: "name2.txt",
    filedata: "data:text/plain;base64,VGhpc.."
}]

My code is

function readFile(file) {
  return new Promise(function(resolve, reject) {
    let fr = new FileReader();
    fr.onload = function() {
      resolve(fr.result);
    };
    fr.onerror = function() {
      reject(fr);
    };
    fr.readAsDataURL(file)
  });
}

// Handle multiple fileuploads
function uploadForm() {
  let files = $('#file')[0].files // ev.currentTarget.files;
  let readers = [];
  if (!files.length) return;
  for (let i = 0; i < files.length; i++) {
    readers.push({
      "filedata": readFile(files[i]),
      "filename": files[i].name
    });
  }
  Promise.all(readers).then((values) => {
    console.log(JSON.stringify(values));
    return
  });
}

function showMessage(e) {
  $('#progress').html(e);
  $('#file').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
  <table cellpadding="5px">
    <tr>
      <td>Select File:</td>
      <td>
        <input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
      </td>
    </tr>
    <tr>
      <td colspan="2"><button onclick="uploadForm();" id="upload">Upload</button>&emsp;</td>
    </tr>
    <tr>
      <td colspan="2">
        <div id="progress"></div>
      </td>
    </tr>
  </table>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I would repair this by just pushing the promises into an array, so you can easily await them all with Promise.all. Then when you get your result array, map it to an array of { filedata, filename } objects.

Here's the different part:

  for (let i = 0; i < files.length; i++) {
    readers.push(readFile(files[i]));
  }
  Promise.all(readers).then((values) => {
    const result = values.map((filedata,i) => ({
      filedata,
      filename: files[i].name
     }));
    
    console.log(JSON.stringify(result));
    return
  });

Your whole example, repaired.

function readFile(file) {
  return new Promise(function(resolve, reject) {
    let fr = new FileReader();
    fr.onload = function() {
      resolve(fr.result);
    };
    fr.onerror = function() {
      reject(fr);
    };
    fr.readAsDataURL(file)
  });
}

// Handle multiple fileuploads
function uploadForm() {
  let files = $('#file')[0].files // ev.currentTarget.files;
  let readers = [];
  if (!files.length) return;
  for (let i = 0; i < files.length; i++) {
    readers.push(readFile(files[i]));
  }
  Promise.all(readers).then((values) => {
    const result = values.map((filedata,i) => ({
      filedata,
      filename: files[i].name
     }));
    
    console.log(JSON.stringify(result));
    return
  });
}

function showMessage(e) {
  $('#progress').html(e);
  $('#file').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
  <table cellpadding="5px">
    <tr>
      <td>Select File:</td>
      <td>
        <input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
      </td>
    </tr>
    <tr>
      <td colspan="2"><button onclick="uploadForm();" id="upload">Upload</button>&emsp;</td>
    </tr>
    <tr>
      <td colspan="2">
        <div id="progress"></div>
      </td>
    </tr>
  </table>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Report

0

The argument to Promise.all() should be an array of promises. readers is an array of ordinary objects, the promises are in the filedata properties. You're just logging those objects, not the result of the promises.

Extract the filedata properties when calling Promise.all().

Then in the Promise.all() callback, you can loop over all the results, and log them along with the corresponding filename from readers.

function readFile(file) {
  return new Promise(function(resolve, reject) {
    let fr = new FileReader();
    fr.onload = function() {
      resolve(fr.result);
    };
    fr.onerror = function() {
      reject(fr);
    };
    fr.readAsDataURL(file)
  });
}

// Handle multiple fileuploads
function uploadForm() {
  let files = $('#file')[0].files // ev.currentTarget.files;
  let readers = [];
  if (!files.length) return;
  for (let i = 0; i < files.length; i++) {
    readers.push({
      "filedata": readFile(files[i]),
      "filename": files[i].name
    });
  }
  Promise.all(readers.map(r => r.filedata)).then((values) => {
    values.forEach((value, i) => console.log(readers[i].filename, JSON.stringify(value)))
  });
}

function showMessage(e) {
  $('#progress').html(e);
  $('#file').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<body>
  <table cellpadding="5px">
    <tr>
      <td>Select File:</td>
      <td>
        <input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
      </td>
    </tr>
    <tr>
      <td colspan="2"><button onclick="uploadForm();" id="upload">Upload</button>&emsp;</td>
    </tr>
    <tr>
      <td colspan="2">
        <div id="progress"></div>
      </td>
    </tr>
  </table>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Report
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!