Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda