Return value when $.getJSON is finished

Asked

Viewed 79 times

0

I have a directory with subdirectories, and the code checks if these subdirectories are valid by consulting the settings.json of them, if it has (which is mandatory to be valid), but the $.getJSON does not work by returning the contents of the file, but rather passing it as argument to a function, however I need the function getThemes return to 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
}
  • What is this variable a in your code? That’s right? It shouldn’t be json or something like that in this push?

  • @Gabrielkatakura yes, I forgot to change, the correct was json

1 answer

2


$.getJSON returns a Promise, as soon as the operation of out.push is done asynchronously, that’s why it’s 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, just use as a Promise normally, and the return in then will be the filtered directories.

getThemes().then(directories => console.log(directories));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.