Creating variable array object with for loop

I have a for loop that pulls data from a MySQL server. I would like the four values to be put into variables so I can use them later. Here's the code I have; for some reason, it says thev is undefined?

create();

function create(){

for(var i=0;i<4;i++){

        var thev=[];

        client.query('SELECT curattend FROM table1 WHERE ind=?',[i], function(err,result){
        thev[i] = result[0].curattend;

        });

        }
        return thev;
}
  console.log(thev[2]);

I would appreciate any advice on this problem.

There are a lot of problems here.

  1. thev is local to create. You don’t assign the return value of create to anything, so it’s still not going to be defined.

  2. var thev = []; should not be inside the for loop. It’ll only end up containing one element. Or it would, but…

  3. The callback to query is not just there for fun; it’s an asynchronous call, and is 100% sure to not have happened by the time you actually return from the function.

I would just do it using the async library:

function range(start, end) {
    var result = [];

    while(start < end) {
        result.push(start);
        start++;
    }

    return result;
}

async.map(range(0, 4), function(i, callback) {
    client.query('SELECT curattend FROM table1 WHERE ind = ?', [i], function(err, result) {
        if(err) return callback(err);
        callback(null, result[0].curattend);
    });
}, function(err, thev) {
    // Continue
});