Search code examples
javascriptnode.jspromisesendgridnew-operator

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)
})

Solution

  • 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;
    }