0

I have a folder with a bunch of JSON files that looks like this:

|
|-foo.json
|-bar.json
|-qux.json
|-baz.json
|-zot.json

Each JSON file has a property children that points to some of the other JSON files, so that they all describe a tree. Now, say that this is foo.json:

foo.json

{
    "id": "foo",
    ...
    "children": [
        "bar.json",
        "baz.json"
    ]
    ...
}

Say that bar.json doesn't have a children property and that this is baz.json:

baz.json

{
    "id": "baz",
    ...
    "children": [
        "zot.json"
    ]
    ...
}

I'm trying to write a Node program that will list the descendants of a given JSON file. Meaning that for foo.json it should output [bar, baz, zot].

I'm using fs-extra to read the JSON files.

If I were doing this synchronously I'd write something like this:

const fs = require('fs-extra');

var descendants = ["foo.json"];
for(var k = 0; k < descendants.length; k++){
    var obj = fs.readJsonSync(descendants[k]);
    if(obj.children) descendants.concat(obj.children);
}
return descendants;

Note: For simplicity, assume that the script executes at the root of the directory where the json files are

But I'd like to do this using promises. My problem is I can't seem to resolve the promise for each file and add the result to the descendants variable before the loop ends, of course because the loop is synchronous.

What is the proper way to do this using promises? In particular, I've been trying to use a combination of Q.js and reduce to help me do this, but I've been unable to write the code properly so far.

Mig82
  • 3,665
  • 1
  • 30
  • 55
  • You can use a `for … of` loop and async/await. Check this answer: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop. Hope it helps. – Jaime Dec 04 '18 at 16:50
  • Also take a look at this npm package: https://www.npmjs.com/package/dependency-graph. I would read all the json files and build a dependency graph using this library and then use `graph.dependenciesOf` to get the dependencies of any file. – Jaime Dec 04 '18 at 16:59

0 Answers0