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

158
Views
Encadenamiento de promesas de Node.js

Soy nuevo en Node.js y puedo ejecutar estos comandos uno por uno usando promesas:

 let promise1 = new Promise(function (resolve, reject) { sftp.connect({ host: host, username: user, privateKey: fs.readFileSync(pemfile) }).then(() => { return sftp.get(remotePath, fs.createWriteStream(localPath)); //This writes from a remote file to a local file }).then(() => { sftp.end(); resolve(); }) .catch(err => { console.error(err.message); reject(err); }); }); await promise1; let promise2 = new Promise(function (resolve, reject) { fs.readFile(localPath, 'utf8', function (err, data) { if (err) { reject(err); } resolve(data); }); }); let data = await promise2;

Esto funciona, pero sé que no es la mejor manera de hacerlo. ¿Hay una mejor manera de hacer esto?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

await se puede usar directamente con métodos que devuelven promesas como sftp.connect , sftp.get , sftp.end para que pueda usarlo directamente y la función esperará hasta que se complete el paso. Solo fs.readfile no devuelve una promesa, pero podemos llamar a fs.promises.readFile() que devuelve la promesa y luego podemos usar await .

El código se puede simplificar:

 try { await sftp.connect({ host: host, username: user, privateKey: fs.readFileSync(pemfile) }) await sftp.get(remotePath, fs.createWriteStream(localPath)); await sftp.end(); let fileData = await fs.promises.readFile(localPath, 'utf8'); console.log(fileData); } catch (error) { console.error(error.message); }

Se ha agregado el bloque try-catch para capturar errores de cualquier acción.

over 4 years ago · Santiago Trujillo 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!