对象中的JavaScript等待

时间:2020-07-24 14:23:50

标签: javascript node.js async-await

我想将项目目录中的文件和文件夹传输到使用NodeJS的对象 我想将“ root”文件夹定义为“ treeview”之类的对象 但是,它记录为“待定” 能帮我解决这个问题吗?

Root folder screenshot

Root folder/assets screenshot

我的NodeJS代码:

import path from 'path';
import {program} from 'commander';
import fs from 'fs';
import util from 'util';

async function getChild(parent){
  const readDir = util.promisify(fs.readdir);

  const dirList = await readDir(parent);

  return dirList.map(async (name) => {
    const dir = path.join(parent, name);
    const isDir = fs.lstatSync(dir).isDirectory();
    
    if (isDir) {
      return {
        type: 'directory',
        name,
        child: getChild(dir),
      }
    } else 
      return {
        type: 'file',
        name,
        child: null,
      }
  });
}

export async function cli(args) {
  let directoryTreeView = {};
  const folderPath = path.resolve('');
  directoryTreeView = Object.assign({}, directoryTreeView, {
    type: 'directory',
    name: 'root',
    folderPath,
    childs: await getChild(folderPath)
  });
}

我得到的结果

{ type: 'directory',
  name: 'root',
  folderPath: 'O:\\rootFolder',
  childs:
   [ Promise { [Object] },
     Promise { [Object] },
   ] 
}

必须

{
  type: 'directory',
  name: 'root',
  child: [
    {
      type: 'directory',
      name: 'assets',
      child: [
        {
          type: 'file',
          name: 'icon1.png'
        },
      ]
    },
    {
      type: 'file',
      name: 'icon2.png',
      child: null,
    }
  ]
}

1 个答案:

答案 0 :(得分:3)

您的getChild不会返回对象数组的承诺,但是会返回对象数组的承诺-map回调为async。这些内在的承诺从未等待过。您只是主要在正确的位置错过了Promise.all通话:

async function getChild(parent){
  const dirList = await fs.promises.readdir(parent);

  return Promise.all(dirList.map(async (name) => {
//       ^^^^^^^^^^^
    const dir = path.join(parent, name);
    const stat = await fs.promises.lstat(dir);
//               ^^^^^ let's do it asynchronously if we can
    
    if (stat.isDirectory()) {
      return {
        type: 'directory',
        name,
        child: await getChild(dir),
//             ^^^^^ needs to be awaited on every call
      }
    } else 
      return {
        type: 'file',
        name,
        child: null,
      }
  }));
}