Drago Drago - 11 days ago 7
Javascript Question

How to access array from the outer functions?

I'm new to asynchronous programming

function loadPlugin(plugins, callback) {
let tests = [[], [], []];
plugins.forEach((plugin) => {
f.isPlugin(plugin, (exists) => {
if (exists) {
if (!f.pluginIsLoaded(plugin)) {
tests[0].push(plugin);
f.loadPlugin(plugin);
} else {
tests[1].push(plugin);
}
} else {
tests[2].push(plugin);
}
});
console.log(tests);
});
return tests;
}


and

module.exports.isPlugin = (plugin , callback) => {
fs.access(`./plugins/${plugin}`, fs.constants.F_OK, (err) => {
callback(!err);
});
};


Inside
f.isPlugin(plugin, (exists) => { });
I push
plugin
into the
tests
array and I
console.log(tests)
from the outer function it shows that the
tests
array is an array containing 3 empty arrays in it.

Is there a way I can retain the the stuff pushed inside
f.isPlugin(plugin, (exists) => { });
so I can access it from the outer functions?

Answer

You could switch from the callback pattern to promises and use Promise.all to wait for all plugin checks to complete:

module.exports.isPlugin = plugin => new Promise( resolve =>
    fs.access(`./plugins/${plugin}`, fs.constants.F_OK, err => resolve(!err))
);

function loadPlugin(plugins) {
    let tests = [[], [], []];
    let promises = plugins.map( plugin => 
        f.isPlugin(plugin).then( exists => {
            let status = !exists ? 2 : +f.pluginIsLoaded(plugin);
            if (!status) f.loadPlugin(plugin);
            tests[status].push(plugin);
        })
    );
    // Turn the array of promises into one promise, 
    // which provides the tests array when it resolves:
    return Promise.all(promises).then( _ => tests );
}

So you would call this as:

loadPlugin(plugins).then( tests => console.log(tests) );