0

I need to read a folder to get the names and from them get the bigger date. folder:

enter image description here

code to read folder, get filenames and get the bigger date(except today):

  async function getLastDate() {
  try {
  let filesNames;
  let today = getDate();
  let returnValue;


fs.readdir(path.join(rutaBase, 'sessionsOffline'), ((err, files) => {
  if (err) {
    console.log('error leyendo directorio');
    return { ok: false, msg: 'Error leyendo directorio en getLastDate', data: null };
  }

  //Obtener las fechas de los archivos(despues del ultimo '_')
  filesNames = files.map(file => {
    if (file.includes('_')) {
      return file.substr(file.lastIndexOf('_') + 1);
    }
  });

  //Remover archivos sin fecha
  let fileNamesFiltrados = filesNames.filter((fileName) => {
    return fileName != null;
  });

  //Remover el archivo de hoy del arreglo
  filesNames = fileNamesFiltrados;
  let arrDatesWithOutToday = [];
  filesNames.forEach(fileName => {
    if (fileName != today) {
      arrDatesWithOutToday.push(fileName);
    }
  });

  //Convertir arreglo a array de tipo Date
  let arrDatesWithOutToday2 = arrDatesWithOutToday.map(val => {
    let [year, month, day] = val.split('-');
    return new Date(year, month - 1, day);
  });

  //Obtener la fecha mayor
  let maxDate = Math.max.apply(null, arrDatesWithOutToday2);

  //Formater la fecha a YYYY-MM-DD
  maxDate = new Date(maxDate).toISOString().split('T')[0];
  returnValue = maxDate;
  return { ok: true, msg: null, data: maxDate };
}));
  } catch (error) {
console.log('probando error: ', error);
return { ok: false, msg: 'Error obtenieno fecha de la ultima sesion', data: null };
    

  }
}

I call getLastDate from another function(line 1936):

enter image description here

but in 1937(console.log('date getBalance: ', date)) Im getting 'date getBalance: undefined' then debugging my code I discovered that callback in fs.readdir is a async function someone can help me? I need get the maxDate in getBalance function(line 1937 of photo). thank you in advance

  • make getBalance async and use await https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await – Moshe Sommers Jan 13 '21 at 22:47
  • 1
    You can't wait for a callback in Javascript.. You need to learn how to program with asynchronous operations in Javascript. Life is often easier than plain async callbacks if you promisify all asynchronous operations and use `async/await`. – jfriend00 Jan 13 '21 at 22:53

2 Answers2

0

First of all, line 1936 is actually an if statement so you have to make sure it falls into the getLastDate() statement.

If so, you can assign the returned value to date in three ways.

Use Promise the getLastDate function such as:

function getLastDate() {
    // Your code
    return new Promise((resolve, reject) => {
        try {
            fs.readdir(path.join(rutaBase, 'sessionsOffline'), ((err, files) => {
                if (err) {
                    reject(err);
                    return;
                }
                // Your code
                resolve({ ok: true, msg: null, data: maxDate });
            });
        } catch (e) {
            reject(e);
        }
    });
}

When you call it:

var date;
if (today) {
    date = getDate();
} else {
    getLastDate().then(res => {
        date = res;
    });
}

Or you can use async/await when you still have the Promise:

async function getBalance() {
    var date;
    if (today) {
        date = getDate();
    } else {
        date = await getLastDate();
    }
}

Or use callback:

function getLastDate(callback) {
    // Your code
    fs.readdir(path.join(rutaBase, 'sessionsOffline'), ((err, files) => {
        if (err) {
            throw err;
        }
        // Your code
        callback({ ok: true, msg: null, data: maxDate });
    });
}

var date;
if (today) {
    date = getDate();
} else {
    getLastDate(res => {
        date = res;
    });
}

They are only concepts, so please ignore my typo and the error check part I omitted.

noob
  • 480
  • 3
  • 20
0

Something like this should work for you:

 function getLastDate() {
    return new Promise( ( res, rej ) => {

      try {
        let filesNames;
        let today = getDate();
        let returnValue;


        fs.readdir(path.join(rutaBase, 'sessionsOffline'), ((err, files) => {
          if (err) {
            console.log('error leyendo directorio');
            res( { ok: false, msg: 'Error leyendo directorio en getLastDate', data: null } );
          }

          //Obtener las fechas de los archivos(despues del ultimo '_')
          filesNames = files.map(file => {
            if (file.includes('_')) {
              return file.substr(file.lastIndexOf('_') + 1);
            }
          });

          //Remover archivos sin fecha
          let fileNamesFiltrados = filesNames.filter((fileName) => {
            return fileName != null;
          });

          //Remover el archivo de hoy del arreglo
          filesNames = fileNamesFiltrados;
          let arrDatesWithOutToday = [];
          filesNames.forEach(fileName => {
            if (fileName != today) {
              arrDatesWithOutToday.push(fileName);
            }
          });

          //Convertir arreglo a array de tipo Date
          let arrDatesWithOutToday2 = arrDatesWithOutToday.map(val => {
            let [year, month, day] = val.split('-');
            return new Date(year, month - 1, day);
          });

          //Obtener la fecha mayor
          let maxDate = Math.max.apply(null, arrDatesWithOutToday2);

          //Formater la fecha a YYYY-MM-DD
          maxDate = new Date(maxDate).toISOString().split('T')[0];
          res({ ok: true, msg: null, data: maxDate });
        }));
      } catch (error) {
        console.log('probando error: ', error);
        res({ ok: false, msg: 'Error obtenieno fecha de la ultima sesion', data: null });
     }
   }
  })

Then:

async function getBalance(){
  ....
  
  if(today) {
    date = getDate();
  } else {
    date = await getLastDate();
  }
  ....
}
  
Getter Jetter
  • 2,033
  • 1
  • 16
  • 37