Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
Valor devuelto desde fs.Readfile() llamado externamente en el nodo

Estoy tratando de obtener un valor devuelto por una función donde leo y escribo un archivo usando fs.readFile/writeFile en Node.

En mi archivo server.js principal, llega una solicitud y luego quiero enviar un correo electrónico desde otro archivo llamado 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();

En sendEmail, primero leo un archivo para obtener el correo electrónico para enviarlo, luego escribo en un segundo archivo y luego, si todo está bien, envío un correo electrónico (desde una función separada):

 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}

Lo que no puedo obtener es un valor para la variable resultOfSend. Sigue volviendo indefinido, creo que porque la promesa aún no se ha cumplido.

¿Cómo obtengo un valor para regresar de la función sendEmail al archivo server.js desde donde se llama?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está utilizando await y async en sendEmail pero no devuelve ninguna Promise (por lo que la función sendEmail no devuelve nada y es por eso que obtiene undefined ). Sin embargo, en la respuesta que intenta llamar a .then() aunque haya usado await .

Entonces deberías:

  1. return Promise en la función sendEmail .
  2. decida cómo quiere manejarlo, si usa async-await entonces no use .then() y simplemente analice la variable y viceversa.
  3. La función generateEmail() también debería devolver Promise .

Por ejemplo:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!