Wednesday, 7 June 2017

Correct way of using async each method to avoid reference errors

I am making a series of database calls, and want to return something once they have all executed.

I am using the async module to help with this and applying a function to each element in an array.

    async.each(items, sqlCall(), 
    function(err) {
        if( err ) {
          // All processing will now stop.
          console.log('A call failed');
        } else {
            console.log("finished async operations");
        }
    });

I define sqlCall as follows

sqlCall = function(item , callback){
        console.log("arr is " + JSON.stringify(item));
        lampInfo = item[0];
        userRoom = item[1];
        sql = item[2];
        console.log('sql is ' + sql);
        connection.query(sql, function(error, results, fields) {
            if (error){
                console.log("why error");
                callback(error);
            }
            else {
                console.log("successful call");
                lampSavingsStatement[savingsCalc(lampInfo, results[0], energyPrice)] = userRoom;
                callback();
            }
        });
    } 

lampSavingsStatement is a global dictionary and savingsCalc is another method

I keep getting a reference error, where arr is undefined, and am not sure what the problem is.

For an example of what items is

[ [ { lampName: '2ft T5 14W', number: '12', hours: '3' },
    'room2',
    'SELECT * FROM `lightstoled` WHERE `techid` = \'2ft T5 14W\'' ] ]



via Abe

No comments:

Post a Comment