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

319
Visualizações
Return value from externally called fs.Readfile() in node

I am trying to get a value returned from a function where I read and write a file using fs.readFile/writeFile in Node.

In my main server.js file, a request comes in and I then want to send an email from another file called sendEmail.js:

const fs = require('fs')
const sendMail = require('./sendEmail')

async function sendAnEmail() {
    let resultOfSend = await sendMail.sendEmail()
    resultOfSend.then((result)=>{
      // return the result
    }        
}

sendAnEmail();

In sendEmail I first read a file to get the email to send to, then write to a second file then, if all is good, I send an email (from a separate function):

async function sendEmail() {
    // Check if user exists
    fs.readFile('./file.json', (err, data) => {
        if(err) {
            throw error
        }
        else {
            let users = JSON.parse(data)
            let dataToWrite = JSON.stringify(users)

            fs.writeFile('./file2.json', dataToWrite, (err) => {
                if(err) {
                    console.error(err)
                    throw error
                }
                else {
                    return generateEmail(users)
                        .then((info) => {
                           return info
                        })
                        .catch(console.log('err'))
                }
            })
        }
    })
}

async function generateEmail(user) {
        let msgText = 'hello world'

        // Set the mail options
        const mailOptions = {
           ...
        }
        
        // Send the mail
    let info = await transporter.sendMail(mailOptions)
    return info
}

module.exports = {sendEmail}

What I can't get is a value for the resultOfSend variable. Keeps coming back undefined, I think because the promise hasn't yet been fulfilled.

How do I get a value to return from the sendEmail function back to the server.js file where it's called from?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're using await and async in sendEmail but not returning any Promise (So the sendEmail function doesn't return anything and this is why you get undefined). Nevertheless, on the response you're trying to call .then() even though you used await.

So you should:

  1. return Promise in the sendEmail function.
  2. decide how you want to handle it, if you use async-await then dont use .then() and just analyze the variable and vice versa.
  3. generateEmail() function should also return Promise.

For example:

async function sendEmail() {
return new Promise((resolve, reject) => {
    // Check if user exists
    fs.readFile('./file.json', (err, data) => {
        if(err) {
            reject()
        }
        else {
            let users = JSON.parse(data)
            let dataToWrite = JSON.stringify(users)

            fs.writeFile('./file2.json', dataToWrite, (err) => {
                if(err) {
                    console.error(err)
                    reject()
                }
                else {
                    generateEmail(users)
                        .then((info) => {
                            resolve(info)
                        })
                        .catch(
                            console.log('err')
                            reject()
                        )
                }
            })
        }
    })
})
}
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