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

91
Visualizações
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 Respostas
Responde à pergunta

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 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