0

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.

1
  • 1
    @minitech That "may" was in regard to "[likely]" (as it's technically possible .. but oh, bother). I should have used stricter language, though - thanks for pointing it out. Commented Jul 25, 2013 at 23:24

1 Answer 1

1

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

I didnt notice the async inside loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.