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

90
Vistas
Promise JavaScript Returning Empty Array

createFolder() function is returning an empty array. I am not sure what I am doing wrong but it needs to return the items within project_array

function get_project_folders(){

  return new Promise((resolve, reject)=>{
    fs.readdir(__dirname + '/projects', (error, data1)=>{
      if(error){
        reject(console.log(`Error. Unable to read directory - ${error}`))
      }else{
        resolve(data1)
      }
    })
  })
}
async function createFolder(){
  let list_of_projects = await get_project_folders()
  let project_array = []


  return new Promise((resolve, reject)=>{
    for(let project of list_of_projects){
      let splitProject = project.split("-")
      fs.readdir(__dirname + `/projects/${splitProject[0]}-${splitProject[1]}`, (error, data1)=>{
        if(error){
          console.log('Error. Unable to read directory.')
        }else{
          project_array.push({circuit: splitProject[0], fuse: splitProject[1], pole: data1})
        }
      })
    }
    resolve(project_array)
  })
}
async function testIt(){
  let folderData = await createFolder()
  console.log(folderData)
}

testIt()
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is a classic, what you are doing is resolving the promise with the empty array before your node fs async methods have resolved. Try this instead:

async function createFolder(){

  const list_of_projects = await get_project_folders();
  const result = await Promise.all( list_of_projects.map(project => new Promise((resolve, reject) => {
    const splitProject = project.split("-");
    fs.readdir(__dirname + `/projects/${splitProject[0]}-${splitProject[1]}`, (error, data1) => {
      if(error){
        console.error('Error. Unable to read directory.');
        resolve( null );
      } else {
        resolve({
          circuit: splitProject[0],
          fuse: splitProject[1],
          pole: data1
        });
      }
    });
  });
  
  // Filter out the errors that resolved as `null`
  return result.filter( Boolean );
  
}

In essence, wrap every fs. call in a promise, then use Promise.all to generate an array of promises. Because Promise.all requires all to be resolved for it to be resolved, make sure you even resolve when there is an error - just return something falsy (in my case null) so you can filter it out later.

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