I am attempting to return an array from a promise using Node.js/Javascript.
'server.js' file:
const db = require('./routes/queries');
function _seedings() {
db.seedlings("hockey")
.then(function(value) {
console.log('I returned this from seedlings: ' + value)
})
.catch(function(err) {
console.log('Caught an error in _seedings!', err);
});
return;
}
'queries.js' file:
function seedlings(_cat) {
return new Promise(function(resolve, reject) {
var _seeds = [];
var _directory = './galleries/pix/' + _cat;
fs.readdir(_directory, (err, files) => {
if (err) {
console.log(err);
} else {
files.forEach(file => {
if (path.extname(file) == ".jpg" || path.extname(file) == ".jpeg") {
_str = file.toString()
_seeds.push(_str);
} //extension is .jpg OR .jpeg
}) //forEach
} //if/else
}) //fs.readdir
resolve(_seeds);
}); //new promise
}
I have used code similar to this to query a database and return the result in the 'resolve'. However with this code I am unable to return an the '_seeds' array. It seems the directory is being read for each file within but from that point either the array is not being populated or it is not being properly returned. Any advice is greatly appreciated.