knex select() returns before completing query in javascript

Viewed 27318

I have a function like this:

function get_projects() {
    var project_names=[];
    knex('projects').select('name').then(function (a) { 
        project_names.push(a);
    })
    return project_names;
}

This function executes the return statement return project_names; before completing project_names.push(a) statement and what I get after calling this function is an empty array, even though my db has results (I can see this if i log within the function a())

3 Answers

I know this is old, but you can do this:

function get_projects() {
    return knex('projects').select('name')
        .then(function (records) {
           // already returns an array you can do other things here
           return records;
        })
}

Now you can do this to access the data.

get_projects()
    .then(function (records) {
        // do what you need as well, like send to the frontend using express
        res.send(records);
    })
Related