1
我在查询(knexjs.org)的for循环中遇到了一些困难。让我们开始如何遍历我的数组。我的阵列看起来像这样:NodeJS用knex迭代速度太快
[ { module_id: 9, able: '1', will: '1' },
{ module_id: 9, able: '1', will: '1' },
{ module_id: 2, able: '1', will: '1' },
{ module_id: 2, able: '1', will: '1' },
{ module_id: 4, able: '1', will: '1' },
{ module_id: 4, able: '1', will: '1' },
{ module_id: 1, able: '1', will: '1' },
{ module_id: 1, able: '1', will: '1' },
{ module_id: 8, able: '1', will: '1' },
{ module_id: 8, able: '1', will: '1' },
{ module_id: 7, able: '1', will: '1' },
{ module_id: 7, able: '1', will: '1' },
{ module_id: 5, able: '1', will: '1' },
{ module_id: 5, able: '1', will: '1' },
{ module_id: 3, able: '1', will: '1' },
{ module_id: 3, able: '1', will: '1' },
{ module_id: 6, able: '1', will: '1' },
{ module_id: 6, able: '1', will: '1' } ]
那么 “好玩” 的部分出现了:
for(var i = 0; i < obj.length; i++) {
var object = obj[i];
console.log("has object", object);
db.knex('interests').where({
inventory_id: inventory_id,
module_id: object.module_id
}).select().limit(1).then(function (result) {
console.log("MODULE ID", object.module_id);
if (result.length == 0) {
db.knex('interests').insert({
inventory_id: inventory_id,
module_id: object.module_id,
could: object.able,
would: object.will
}).then(function (a) {
});
} else {
db.knex('interests').where({
inventory_id: inventory_id,
module_id: object.module_id
}).update({
could: object.able,
would: object.will
}).then(function (a) {
});
}
});
}
什么代码所做的是以下几点:
- 迭代通过数组
- 查询数据库
- 如果没有结果,请创建一些东西
- 如果结果,更新内容
只有一个问题。 For循环也是也是快。或换句话说:查询太慢了。为什么?因为object.module_id始终是数组中的最后一个module_id。
我该如何确保它使用for循环中的module_id,而不是上次迭代时给出的变量?
我们快到了,感谢您的帮助迄今为止...然而,在queryinterest,'返回q_result'返回未定义,因为查询尚未完成...那么如何解决? – Thijmen
哎呦,我想我犯了一个'q_restult'而不是'q_result',我编辑了我的代码! –
这也行不通。在再次编辑“q_result = result” – Thijmen