Return value when $ .getJSON finishes

0

I have a directory with subdirectories, and the code checks if these subdirectories are valid by querying the settings.json of them, if it has (which is required to be valid), however $.getJSON does not work by returning the contents of the file, and if I pass it as an argument to a function, however I need the getThemes function to return the list of valid subdirectories when all $.getJSON are ready, code:

getDirectories = (srcpath) => {
    return fs.readdirSync(srcpath).filter(function(file)
    {
        return !['.', '..'].includes(file) && fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

getThemes = () => {
    let directories = getDirectories(path.join(process.cwd(), 'themes'));
    let out = [];

    for (let dir of directories)
        $.getJSON(path.join('themes', dir, 'settings.json')).done((json) => {
            if (json.version && json.name)
                out.push(json)
        })

    return out
}
    
asked by anonymous 23.07.2016 / 04:28

1 answer

2

$.getJSON returns a Promise , so the operation of out.push is done asynchronously, so it is returning out empty. To resolve this, you will have to return a Promise in getThemes .

getThemes = () => {
    let directories = getDirectories(path.join(process.cwd(), 'themes'));
    let directoriesAsPromise = directories.map(dir => {
        return new Promise((resolve, reject) => {
            $.getJSON(path.join('themes', dir, 'settings.json')).then(resolve, reject);
        });
    }); 

    return Promise.all(directoriesAsPromise).then(results => {
        return results.filter(json => json.version && json.name);
    });
};

To use, you only need to use as Promise normally, and return then will be the filtered directories.

getThemes().then(directories => console.log(directories));
    
23.07.2016 / 04:41