我尝试将一些数据插入到循环内的数据库中。问题是它总是插入相同的值(第一个)。我的意思是即使我的变量的值不同(我将它显示在控制台上,这样我就可以在查询数据库以插入它之前检查一切是否正常)。
我的程序基于 Node.js。
这是我的代码示例:
var obj = JSON.parse(result.body);
global.store_urls = [];
for (let i = 0; obj.productEntities.length > i; i++){
global.store_urls.push(obj.productEntities[i].url);
var reference=obj.productEntities[i].IdProduct;
var brand=obj.productEntities[i].Brand;
var price=obj.productEntities[i].Price;
var new_price=obj.productEntities[i].PriceNew;
var reduction=obj.productEntities[i].sale_state;
var type_1=obj.productEntities[i].Category;
var sold=obj.productEntities[i].sold;
console.log(reference+" / "+brand+" / "+price+" / "+new_price+" / "+reduction+" / "+type_1+" / "+sold);
//Row (data) insertion part
var sql = mysql.format("SELECT * FROM vd_tendance WHERE url=?", [obj.productEntities[i].url]);
var selectUrl = connection.query(sql, function(err,rows,fields) {
if(err){throw err;}
//Checking the value exist on the table
if(rows.length > 0){
//If already exists, no need to insert
console.log(rows.length);
}else{
//Save to database
connection.query('INSERT INTO `vd_tendance` VALUES ( NULL , ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP())',
[ reference,
type_1,
brand,
price,
new_price,
reduction,
sold,
url,
]
, function (err, result) {
if (err) {console.error('error inserting into database : ' + err.stack); return;}
else{}
});
}
});
}
结果始终是插入到每一行的相同数据(变量采用的第一个值)。
你能给我一些解决这个问题的想法吗?也许它与异步节点js系统完全相关?
谢谢你们 !
在调用给异步函数的回调之前,循环完全执行。
一种解决方案是将数组项捕获在闭包中,例如使用 forEach:
obj.productEntities.forEach(function(entity){
global.store_urls.push(entity.url);
var reference = entity.IdProduct;
...
另请注意,在进行查询之前仍会执行整个循环,如果后面的代码取决于正在更新的数据库,则这可能是一个问题。在这种情况下,您最好查看处理异步任务的现代解决方案:
require('async')
)本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句