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

215
Visualizações
Get the array value of a promise

I'm trying to send multiple attachments with Sendgrid with a new promise as below. I want to return an array of objects but I don't understand how to do so. emailAttachments contains my 3 objects, but how can I return the array? Can you tell me what's wrong in my code?

const emailAttachments = []

return new Promise(function(resolve, reject){

    pdfList.map(item => {

        fs.readFile((item.frDoc), (err, data) => {
            if (err) {
              return { handled: false }
            }

            if (data) {
                
                emailAttachments.push({
                    content: data.toString('base64'),
                    filename: `document.pdf`,
                    type: 'application/pdf',
                    disposition: 'attachment'
                })

            }
        });
    })

    resolve(emailAttachments)
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are mixing callback functions and promises. That won't work. I'd suggest to use the promise API of the fs module supported since node 10.

Furthermore, you need to await the filereading before resolving promise, which you currently don't do.

import { promises as fsp} from "fs"; //use the Promise API from fs

async function getAttachments(pdffiles) {
  return Promise.all(pdffiles.map(pdf => fsp.readFile(pdf.frDoc)))
    .then(files => files.map(f => ({
       content: f.toString("base64"),
       filename: "document.pdf",
       type: "application/pdf",
       disposition: "attachment"
     })));

}
about 4 years ago · Juan Pablo Isaza Relatório

0

I think you need something like this:

async function getEmailAttachments(pdfList) {
    const emailAttachments = await Promise.all(pdfList.map((item) => {
        return new Promise(function (resolve, reject) {
            fs.readFile((item.frDoc), (err, data) => {
                if (err) {
                    reject({ handled: false });
                }
                if (data) {
                    resolve({
                        content: data.toString('base64'),
                        filename: `document.pdf`,
                        type: 'application/pdf',
                        disposition: 'attachment'
                    });
                }
            });
        });
    }));
    return emailAttachments;
}

[EDIT] Or using the promise version of readFile (sugestion of @derpirscher):

async function getEmailAttachments(pdfList) {
    const emailAttachments = await Promise.all(pdfList.map(async (item) => {
        const data = await fs.promises.readFile(item.frDoc);
        return {
            content: data.toString('base64'),
            filename: `document.pdf`,
            type: 'application/pdf',
            disposition: 'attachment'
        };
    }));
    return emailAttachments;
}
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