0

I'm attempting to iterate over a list of xml files, convert the xml content to js objects and then grab some data from the object, ultimately generating an array with one element from each xml file.

Given the asynchronous nature of readfile, I'm trying to create promises for each file and fulfill those promises when the process is done, thus allowing my calling function to act on the array of data from my promises once the async process is complete. This is not going as planned, so I'm hoping that someone can steer me in a better direction.

Keeping in mind that I am brand new to the world of js / ts. :\

Thanks!

Calling function

getBoards(boardPath)
        .then(result => {console.log(result);});

Async promises function

export function getBoards(examplesPath: string): Promise<any> {
    let examplesManifestPath = path.join(examplesPath, 'manifests');
    let parser = new xml2js.Parser();
    let boardNames: Array<string> = [];

    let files = fs.readdirSync(examplesManifestPath).filter(fn => fn.endsWith('.xml'));
    let promises: any = [];

    files.forEach(file => {
        promises.push = new Promise(function (resolve, reject) {
            fs.readFile(path.join(examplesManifestPath, file), function(err, data) {
                parser.parseString(data, function (err: string, result: any) {
                    return result['data']['boards'][0]['board'][0]['$']['name'];
                });

            });
        });
    });

    return Promise.all(promises);
}
  • 2
    You have to `resolve(your_value)` and not `return your_value` from a callback who's caller doesn't care what it returns. – Quentin May 28 '21 at 15:14
  • 1
    You can use `const fs = require('fs').promises;` to use async readFile instead of building yours – Nicolas Menettrier May 28 '21 at 15:18
  • 2
    `promises.push` is a function. Call it and pass an argument. Don't overwrite it with a promise. – Quentin May 28 '21 at 15:43
  • @Quentin - Just noticed that and made the fix. The array is populated by promises, not the promiseResult is never resolving after changing the return to a resolve. – adas userinski May 28 '21 at 15:47
  • 2
    Well yes. The array is *supposed* to be populated with promises. The argument you pass to `Promise.all` **needs** to be an array of promises. (At some point in the future the promises in the array will become resolved promises with the values you resolved them with) – Quentin May 28 '21 at 15:49
  • Got it to resolve properly and return the correct data. Appreciate all of your help, and now I have a much better understanding of what's happening in the wonderful world of promises. – adas userinski May 28 '21 at 16:01

0 Answers0