1

I am trying to return an array of numbers in a Javascript function.

function getSeasons() {
    db.any('select season from video', [true]) //recieving unsorted data
        .then(function (data) {
        let sorted = new SortedSet(); // creating SortedSet from collections.js
        data.forEach(function (item) {
            sorted.push(item.season) // fills set with data
        });
        console.log(sorted.toArray()) // works fine
    })
        .catch(function (error) {
            console.log(error)
        })
    }
}

That console.log(sorted.toArray()) works fine and in a console I recieve log like [1, 2, 3, 4, 5]. But if I'm trying to make return sorted.toArray() - result of it is undefined. Why?

The question is if we have something like ( this is a simplified version of the code above)...

function getArray() {
var array = [1, 2, 3];
//return ??
}

...how to get this [1, 2, 3] using getArray()?

ekhodzitsky
  • 103
  • 1
  • 1
  • 10
  • 1
    return array; ? Not sure what else you are looking for. If you just want to return the array then return it. – basic Jan 31 '19 at 00:27
  • Where is your return sorted.toArray() line? It's not in your code so where are you actually specifying it? – basic Jan 31 '19 at 00:28
  • You're saying "( this is a simplified version of the code above)", but no it isn't. You can't just simplify code you do not understand. In any case, you'll want to look into how to return data from an asynchronous function. Read a bit about callbacks and promises and try to get familiar with the asynchronous nature of Node. – Azami Jan 31 '19 at 00:29

0 Answers0