Promise JavaScript 返回空数组

Promise JavaScript Returning Empty Array

createFolder() 函数是 returning 一个空数组。我不确定我做错了什么,但它需要 return 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()

这是一个经典,你正在做的是在你的节点 fs 异步方法解析之前用空数组解析承诺。试试这个:

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 );
  
}

本质上,将每个 fs. 调用包装在一个承诺中,然后使用 Promise.all 生成一个承诺数组。因为 Promise.all 需要解决所有问题才能解决,所以确保在出现错误时解决 - 只是 return 一些虚假的东西(在我的情况下 null)所以你可以过滤稍后再出来。