Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda