0

I'm having trouble with some asynchronous database queries. I'm using the Async library for Node.js. I have some code forming an object before it hits the add() function. In my code, I have a loop the executes to create the object multiple times.

for(var i = 0; i < 10; i++){ 
    var obj.id = i + '_idstring';
    add(obj);
}

As you can see, each object is slight different. I need to perform a lookup in my database to see if the object already exists (1st waterfall function) and if it does not, add it to my database (2nd waterfall function). My issue is, loaObj.id always equals 10_idstring. Is this a problem with how I'm passing the object through the callbacks? How should I be handling this?

function add(loaObj) {
    async.waterfall([
        function(loaObj, callback) {
            var sql = "";
            connection.query(sql, function(error, results, fields) {
                callback(error, results, loaObj);
            });
        },
        function(results, loaObj, callback) {
            if (results.length > 0) {
                sendMessage();
            } else {
                var sql = "";
                connection.query(sql, function(error, results, fields) {
                    callback(error, loaObj);
                });
            }
        }
    ], function(err, loaObj) {
        console.log(err);
        if (err) {
            sendMessage();
        } else {
            sendMessage();
        }
    });
}
2
  • Your first code snippet isn't valid JS because object properties like obj.id can't be declared with keywords like var or let. You should be able to just do something like add({ id : i + '_idstring' }) though Commented Aug 4, 2017 at 23:50
  • Your loop is changing the same object, and loadObj is going to refer to that same object. You should be creating a new object in each iteration of the loop. Commented Aug 4, 2017 at 23:50

1 Answer 1

1

Because you are using Object, which will be passed by "copy of a reference", then obj.id will be overridden with every loop and it will settle down to 10_idstring -where the loop stops-. One simple solution is to pass new Object every time like below:

for(var i = 0; i < 10; i++){ 
  add({id: `${i}_idstring`});
}
Sign up to request clarification or add additional context in comments.

Comments

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.