How to return a value from a function

72 Views Asked by At

I have an ArangoDB function that queries all the documents in the instanceCollection, inside databasehelper.js:

listInstances = function listInstances() {
    var instances = db.query(aqlQuery`
    FOR doc in instanceCollection
    RETURN doc
    `).then(
        cursor => cursor.all()
    ).then(
        result => {
            return result;
        }
    )
    return instances;
}

Also, I want to use this function to reflect the JSON query to an Express API:

app.get('/', function(req, res) {
    var allInstances = databasehelper.listInstances();
    res.send(allInstances);
});

The api result was nothing but an empty JSON {}. How can I reflect the result of my ArangoDB query to my Express API call?

1

There are 1 best solutions below

0
On BEST ANSWER

Understand how promises work. The following is an idea on how it should be designed.

databasehelper.js => Return a promise

listInstances = function listInstances() {
    return db.query(`some query`)
    .then(cursor => cursor.all())
}

in the route, => fetch the data from the promise

app.get('/', function(req, res) {
    databasehelper.listInstances()
    .then(result => {
        res.send(result);
    })
});