const randomGIFFunc = async function(dirname) {
const dirPath = 'src/gifs/' + dirname;
fs.readdir(dirPath, (err, files) => {
if (err) {
console.log('Error reading directory: ', err );
return;
}
const randomIndex = Math.floor(Math.random() * files.length);
const randomGIFname = files[randomIndex];
const randomGIFpath = dirPath + '/' + randomGIFname;
console.log('arr in function: ' + [randomGIFpath, randomGIFname]);
return [randomGIFpath, randomGIFname];
})
}
later in async code
switch (act) {
case 'hug':
const arr = await randomGIFFunc('hug');
console.log("arr: " + arr); //undefined
const randomGIFpath = await arr[0];
const randomGIFname = await arr[1];
break;
terminal:
arr: undefined
There was an error running this command: TypeError: Cannot read properties of undefined (reading '0')
arr in function: src/gifs/hug/01.gif,01.gif
Everything I tried is already in code I gave
I can only guess that for some reason the function actually happens later (judging from the terminal logs), but I have no idea why the code isn't waiting for it to finish
randomGIFFunc()doesn't return anything.I have no idea why code isn't waiting for it to finish....because callbacks are designed to be executed later after something external completes. So your code doesn't run until the readdir operation completes and runs the callback you provided to it. That doesn't block the outer function from executing. Make sure you understand asynchronous operations. You didn't await it, so it doesn't block the code you called it from. And youreturned from the callback, not from randomGIFFunc(), so the returned value will go back the code infsthat triggered the callback - and it doesn't care.