Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda