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

205
Visualizações
How to break out a loop in a callback

hi how can I break out of the for loop ? I want to be able to break out of it in the callback in the if statement

I want this program to create a folder in the given directory and every time it throws an error I want it to change the folder name and add a number to it so when it says that the folder already exists, It'll create a unique folder name until it doesn't throw an error.

I will check for the error code later help me solve this first

const path = require('path');

function folder(folderName) {

    for (let i = 1; i <= 10; i++) {
        let pathNumber = i;
        let fullPath = folderName + pathNumber;

        fs.mkdir(path.join("D:", fullPath), (err) => {

            if (!err) {
                return; // I want to break out of the loop here
            }

        })
    }
}

folder("folder");
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Much simpler without await

const numFolders = 10,
folders = Array.from(Array(numFolders), (_,i) => `folder${i+1}`), len = folder.length;
let cnt = 0;

const makeFolder = () => {
  if (cnt >= len) return; // stop because done
  fs.mkdir(path.join("D:", fullPath), (err) => {
  if (err) {
     makeFolder(); // only call again if error
  }
  cnt++
}
makeFolder()
about 4 years ago · Juan Pablo Isaza Relatório

0

You can't write the code that way because the for loop will already be done before any of the fs.mkdir() callbacks are called. They are asynchronous and happen LATER.

If you want to execute one iteration of the loop, including the fs.mkdir() before moving on to any other, then you can use async/await with fs.promises.mkdir().

Here's what a solution could look like with fs.promises.mkdir(). I've also added error handling for the case where all 10 sub-dir names you're trying already exist.

async function folder(folderName) {
    let lastError;
    for (let pathNumber = 1; pathNumber <= 10; pathNumber++) {
        let fullPath = path.join("D:", folderName + pathNumber);
        try {
            await fs.promises.mkdir(fullPath);
            return fullPath;
        } catch(e) {
            lastError = e;
            // ignore error so we keep trying other numbers
        }
    }
    throw lastError;
}

folder("folder").then(fullPath => {
   console.log(`dir created: ${fullPath}`);
}).catch(err => {
   console.log(err);
});
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