[英]Issue with node.js loop and db queries
I have to run mysql queries in a loop in Node.js, but what i know it cannot be done in a way I wanned to. 我必须在Node.js中循环运行mysql查询,但是我所知道的无法以我想要的方式完成。
Here is waht I want to achieved: 这是我要实现的目标:
for(var attributename in body){
sql.increaseValue(attributename, body[attributename]);
}
I go to parse and JSON object in which i do not number or names of attributes nor its values. 我去解析和JSON对象,在其中我没有属性的编号或名称,也没有其值。 I know I need to use some kind of callback pattern.
我知道我需要使用某种回调模式。 I've read many articles about that but in this case i can't move on
我已经读过很多关于此的文章,但在这种情况下,我无法继续
Thanks in advance 提前致谢
Radek 拉德克
I assume that what you want is to know when all of these operations end? 我假设您想知道所有这些操作何时结束? When the loop ends?
循环何时结束? This can be achieved in multiple ways.
这可以通过多种方式来实现。 I assume that your
.increaseValue
method accepts a completion callback. 我假设您的
.increaseValue
方法接受完成回调。 If that's the case, then here's a pseudocode: 如果是这样,那么这里是一个伪代码:
var finalize = function( ) {
// for finalization after the loop
};
var requests = [];
for (var attributename in body) {
(function(attr){
var req = function() {
sql.increaseValue( attr, body[ attr ], function( ) {
var idx = requests.indexOf( req );
if (idx !== -1) {
requests.splice( idx, 1 );
}
if (!requests.length) {
finalize( );
}
} );
}
requests.push( req );
})(attributename);
}
// second loop
for (var i = 0; i < requests.length; i++) {
requests[i]( );
}
Few things worth noting: 几件事值得注意:
1) If .increaseValue
is truely asynchronous, then you can take advantage of the fact that NodeJS is single-threaded and you can get rid of the second loop and simply call req( )
after requests.push( req );
1)如果
.increaseValue
是异步的,那么您可以利用.increaseValue
是单线程的事实,并且可以摆脱第二个循环,而在requests.push( req );
之后简单地调用req( )
requests.push( req );
. 。 However if by any chance
.increaseValue
fires synchronously ( for example when an error occures or something ), then this may cause finalize
to fire immediatly. 但是,如果任何时候
.increaseValue
同步触发(例如,当发生错误或某些错误时),则可能会导致finalize
立即触发。 So do this with caution. 因此,请谨慎操作。
2) You need to wrap req
definition with an anonymous function because of the scoping. 2)由于作用域,您需要使用匿名函数包装
req
定义。
3) Have a look at caolan's Async.js library . 3)看一下caolan的Async.js库 。 It might help you greatly with this problem.
它可能会大大帮助您解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.