I am trying to export an array from a JavaScript function, but there seems to be an issue. The code for the function is the following:
function fetchThemesList() {
let themes = new Array()
let options = {(...)}
request(options, function(error, response, body) {
let i = 0;
JSON.parse(body).forEach(element => {
themes.push(element.name)
//console.log(themes) debug
});
return themes;
})}
fetchThemesList();
What I want to do is return the value of the themes
variable, but regardless of what I do, it just won't work. When using console.log
in the function itself I'll either get undefined
or an empty array ([]
). But when I try to log inside of the function, removing the comment mark, I will see the results being added to the array:
$ node themes.js
undefined
[ 'result-zero' ]
[ 'result-zero', 'result-one' ]
It seems like the function is being executed async, and the blank array is being output first, but I've tried using Promises with the same code and got the same results.
Thanks in advance.