内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我试图使用数组将多个值插入NoSQL数据库Cassandra,但是当我使用下面的代码时,而不是为存储在foo5
它最后只添加了两行。中添加的两行包含相同的值。col5
和col3
var insert2 = "INSERT INTO content (col, col2, col3, col4, col5) VALUES (?, ?, ?, ?, ?);" for(var i = 0; i < foo5.length; i++) { client.execute(insert2, [foo, foo2, foo3, foo4, foo5[i]], {prepare : true}, function(err, result) { if(err) throw err; }); }
例如,这就是结果(col
是主键):
col | col2 | col3 | col4 | col5 ---------+---------+-----------+--------+-------- 8909265 | text | 8759 | 5332 | 7480 1769288 | text | 8759 | 5332 | 7480
我想为数组中的每个值添加一行foo5
。这是预期的结果。我如何做到这一点:
col | col2 | col3 | col4 | col5 ---------+---------+-----------+--------+-------- 8909265 | text | 8759 | 5332 | 1234 1769288 | text | 8759 | 5332 | 5678 3254786 | text | 8759 | 5332 | 9101112 4357234 | text | 8759 | 5332 | 1314151617
假设foo5 = {1234, 5678, 9101112, 1314151617};
这是因为Node.js是异步的。可以对此使用承诺,或者使用递归函数代替循环。
通过使用递归函数代替循环,将使它能够完成。client.execute
而不是用不同的数据再次触发。通过使用for循环,只需调用client.execute
用同样的数据。
例如(对于Node.js中的递归,请注意有更好的方法来编写它,但我希望使它变得简单,以便能够理解语法):
function recursion(i, howManyTimes){ //First you define function if(i === howManyTimes){ //If it's called enough times just escape recursion return; }else{ //Your code for DB should be here, after successful .execute call call line under this one! recursion(++i, howManyTimes); } } recursion(0, 5); //You can call your function now since you defined it