简体   繁体   English

来自for循环的变量始终返回0

[英]Variable from for loop always returns 0

I am reasonably new to node.js / sails.js and have run into a problem that I know the answer is simple but I cannot seem to work it out. 我对node.js / sails.js相当陌生,遇到了一个我知道答案很简单但似乎无法解决的问题。

My code is as follows 我的代码如下

SendCompleted : function(req,res)
    {
        var updated = 0;
        var params = req.params.all();
        var dt = JSON.parse(decodeURI(params.id));
        var connection = new sql.Connection(testrmis, function (err)
        {
            if (err) {

            }
            for(var i = 0; i < dt.length; i++) {
                var obj = dt[i];
                var request = new sql.Request(connection);
                request.stream = true;
                request.input('branchid', sql.Int(), obj.branch_id);
                request.input('picklistid', sql.Int(), obj.picklist_id);
                request.input('scanned',sql.Int(),obj.scanned);
                request.input('expected', sql.Int(),obj.expected);
                request.input('poscode', sql.VarChar(),obj.poscode);
                request.input('label', sql.VarChar(), obj.label);
                request.input('dt', sql.VarChar(), obj.dt);
                request.execute('WAREHOUSE_InsertPiPackData');
                request.on('done', function(returnValue) {
                    updated = updated + returnValue;
                    console.log(updated);
                });
            }
            res.send("[{\"ReturnValue\":" + updated + "}]");
        });

    }

I am sending in 4 lines of results and my console.log(updated) counts up as it should for each line, eg 1,2,3,4 我要发送4行结果,并且console.log(updated)会按行计数,例如1,2,3,4

However the res.send result for updated is always 0. 但是,更新的重新发送结果始终为0。

Could anyone please explain why this is happening? 谁能解释为什么会这样吗? My var updated is outside of my loop and this is getting updated correctly, however when the loop is finished it seems to get reset to 0? 我的var更新在我的循环之外,并且正在正确更新,但是当循环结束时,它似乎重置为0?

returnValue == @@rowcount from the stored procedure returnValue == @@ rowcount来自存储过程

request is async so requestasync

res.send("[{\"ReturnValue\":" + updated + "}]");

gets executed even before you get the callback on request as JS doesn't wait for the callback and executes the next line. 即使在您请求获得回调之前也要执行,因为JS不等待回调并执行下一行。 What you can do is use a counter and place your res.send inside for loop. 您可以做的是使用counter然后将您的res.send到for循环中。

SendCompleted : function(req,res)
    {
        var updated = 0;
        var params = req.params.all();
        var dt = JSON.parse(decodeURI(params.id));
        var connection = new sql.Connection(testrmis, function (err)
        {
            if (err) {

            }
            for(var i = 0; i < dt.length; i++) {
                var obj = dt[i];
                var count = dt.length; //COUNTER
                var request = new sql.Request(connection);
                request.stream = true;
                request.input('branchid', sql.Int(), obj.branch_id);
                request.input('picklistid', sql.Int(), obj.picklist_id);
                request.input('scanned',sql.Int(),obj.scanned);
                request.input('expected', sql.Int(),obj.expected);
                request.input('poscode', sql.VarChar(),obj.poscode);
                request.input('label', sql.VarChar(), obj.label);
                request.input('dt', sql.VarChar(), obj.dt);
                request.execute('WAREHOUSE_InsertPiPackData');
                request.on('done', function(returnValue) {
                    counter--;
                    updated = updated + returnValue;
                    console.log(updated);
                    if(counter == 0) res.send("[{\"ReturnValue\":" + updated + "}]");
                });
            }
        });

    }

Try for this: 为此尝试:

May be Async problem: 可能是异步问题:

for(var i = 0; i < dt.length; i++) {    
//Your logic    
  if(i=== dt.length){
     res.send("[{\"ReturnValue\":" + updated + "}]");
  }    
}

This is because at the time you do request.send, the value of updated is not incremented. 这是因为在您执行request.send时,updated的值不会增加。 This is because request.execute is asynchronous and done handler will be invoked after the res.send has been executed. 这是因为request.execute是异步的,res.send执行后将调用done处理程序。

I would recommend a promise library (example, q). 我会推荐一个Promise库(例如q)。 You can combine the promises and then use Q.all to do req.send when all the promises are done. 您可以合并承诺,然后在完成所有承诺后使用Q.all进行req.send。

See more details here 在这里查看更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM