I have a problem where I call a function that is supposed to return a list, while also assigning the return value of that function to a variable, which is undefined. I suspect this has to do with the fact that I am fetching data from the realtime database (firebase), by using get, and such functions always execute after the fact, meaning that my function returns a value before the value gets created in the get function. I do not know exactly how to solve it, but I have had similar problems in Swift, hence the suspicion that the cause is the compilation hierarchy.
This is the function:
export default function createRoutes() {
const db = getDatabase(app);
const dbRef = ref(db);
get(child(dbRef, `parties`))
.then((snapshot) => {
const data = snapshot.val();
var paths = Object.keys(data);
let completeArray = [];
for (const path of paths) {
completeArray.push({
type: "collapse",
name: path,
key: path,
route: "/" + path,
component: <SvgBeta />,
});
}
return completeArray;
})
.catch((error) => {
console.error(error);
});
}
In my index.js file, I then call this function and assign the return value to a variable.
var hello = createRoutes();
console.log(hello);
This logs 'undefined' If I were to log the return value (completeArray) inside of the function, it would log correctly, I have tried that.
How do I solve this issue, so that the variable hello will equal the completeArray value, as it looks towards the end of the execution of the function?
createRoutes has no return statement, so it's implicitly returning undefined. There is a return statement inside the .then callback, but all that does is control what the promise resolves to. You will need to return the promise for it to be available to the outside world:
export default function createRoutes() {
const db = getDatabase(app);
const dbRef = ref(db);
// Added "return" to the next line
return get(child(dbRef, `parties`))
.then((snapshot) => {
// ..etc
}
// used like:
createRoutes().then(hello => {
console.log(hello);
});
Note that you will be returning a promise that resolves to the array, not the array itself. It's not possible to return an array, because that array doesn't exist yet (it needs to be fetched from the database first).