0

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.

Pangit
  • 564
  • 1
  • 7
  • 23

1 Answers1

0

You need to resolve promise with required data i.e. _seeds array in your case once all files are iterated. Since you are calling resolve from outside of callback function for readdir, promise is getting resolved before readdir is complete.

Changing queries.js to following should work:

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); 
       reject(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
       
       // Resolve after all files are iterated and _seeds is populated.
       resolve(_seeds);
     }  //if/else 
   })  //fs.readdir

  }) // Promise
}

Raeesaa
  • 3,267
  • 2
  • 22
  • 44
  • Thank you for that information. I made the adjustment and now the array seems to be returning the populated information. Much appreciated! Regards. – Pangit Feb 09 '21 at 02:06