Ben Ben - 1 month ago 15
Node.js Question

Node.js - load and execute multiple functions using Promise.all()

I am developing a "plugins" concept whereby I have a series of files, each containing a single function (a plugin). I would like to automatically load and execute these using

promise.all()
.

Problem: each plugin function does not execute.

Here is my example plugin
plugins/example.js
:

"use strict";

exports = function() {
return new Promise(function(resolve, reject) {
console.log("Plugin running....");
setTimeout(resolve, 200, 'example plugin succeeded!');
});
};


From my app.js I then load all plugins using the require-all NPM module:

const plugins = require('require-all')(__dirname + '/plugins');


I then try to execute all as part of my promise chain:

return Promise.all([plugins]);


No logging takes place from the function. Interestingly when I log the contents of
plugins
, I see and empty object:

{
"example": {}
}


Can anyone advise why the example function is not being called?

Answer

The RequireAll plugin returns an object containing the plugin name as a key, and the import as the value, so you'll have to get the values and then call those functions to get the promises, and then you'd have an array of promises

const plugins = require('require-all')(__dirname + '/plugins');

var promises  = Object.keys(plugins).map(function(key) {
    return plugins[key]();
});

Promise.all(promises).then(function() {
    // all done
}).catch(function(err) {
    // fail
});