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

93
Visualizações
Node.js promise chaining

I am new to Node.js and am able to run these commands one by one one using promises:

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;

This works but I know this is not the best way to do this. Is there a better way to do this?

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

0

await can be used directly with methods that return promise like sftp.connect, sftp.get, sftp.end so you can use it directly and the function will wait until the step is completed. Only fs.readfile does not return a Promise but we can call fs.promises.readFile() that returns promise then we can use await.

The code can be simplified:

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

The try-catch block has been added to capture errors from any action.

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