Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement