首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在nodejs for循环中插入语句?

在nodejs for循环中插入语句?
EN

Stack Overflow用户
提问于 2018-06-02 08:24:13
回答 2查看 2.8K关注 0票数 1

我尝试使用一个数组将多个值插入到nosql数据库cassandra中,但是当我使用下面的代码时,并没有为存储在foo5中的每个值添加一行,结果只是添加了两行。添加的两行在col5col3中包含相同的值

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};

更新:

按照someRandomSerbianGuy的建议添加一个递归函数后,我的代码如下所示:

function recursion(i, counter) {
    var insert2 = "INSERT INTO content (col, col2, col3, col4, col5) VALUES (?, ?, ?, ?, ?);"
    if(counter == i) {
        return;
    } else {
        client.execute(insert2, [foo, foo2, foo3, foo4, foo5[i]], {prepare : true}, function(err, result) {
            if(err) throw err;
            recursion(++i, counter);
        });
    }
}
recursion(0, foo5.length);

我仍然得到相同的结果。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-18 03:01:35

切换到代理客户端模块并使用异步功能。您需要研究Node中的promises和异步函数。这将需要一些时间来适应它,但这是必要的,因为这种类型的问题在回调中经常发生。

代码将变得更简单,并且它将以更直接的方式工作,一次一个插入:

async function insert(sql, data) {
  for (let i=0; i<data.length; i++)
    await client.insert(sql, data[i]);
}
票数 1
EN

Stack Overflow用户

发布于 2018-06-02 08:34:28

这是因为Node.js是异步的。您可以使用Promises for this,或者使用递归函数代替for loop。

通过使用递归函数而不是for循环,您可以让它完成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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50652437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档