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

98
Visualizações
How to wait till a task runs to completion in Node JS

I have an array of image urls. Once I download all the images successfully, post completion, I want to write output to a separate file in Node/Express.

funtion extractImages(elems) {

Array.from(elems).filter((url) => {
            console.log("url tried", url);
            var _name = url.split('/').pop(-1).toLowerCase().replace("%20", "-");
            console.log("_name tried", _name);
            var file = fs.createWriteStream(_name);
            https.get(url, function(response) {
                console.log("*******downloaded********");
                response.pipe(file);
                file.on("finish", () => {
                    file.close();
                    console.log("Download Completed, set image now *****", `url(${_name})`);
                });
            });
    })
}
router.post('/api/stuff', async (req, res, next) => {
    // .....
    // .....
    var arr = ['...','...'];
    extractImages(arr);
    // only do it post images are downloaded
            filename = uuid();
        fs.writeFile(`${filename}.html`, dom.serialize(), function (err) {
            if (err) throw err;               
            console.log('Results Received, file writen');
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({ done: "test" }));
        }); 

But because images downloading takes some time, fs.writeFile runs before. I could wait by setTimeout and passing a delay, but in this scenario what's a better approach to handle the same?

UPDATE

If I put the writeFile inside file.on("finish", callback that runs multiple times for all elements in the array. I want to run and write the file only once.

about 4 years ago · Juan Pablo Isaza
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