简体   繁体   English

迭代如何等待Node.js中的sqlite3查询?

[英]How can an iteration wait for a sqlite3 query in node.js?

I have something like this: 我有这样的事情:

async.forEach(JSONfile,function(item,next){                      
  insertData(item.guid,item.size,item.price,item.latitude,item.longitude,item.property_type,function(){                    
    next();
   });
//code after the insert into db

});

And the function : 功能:

function insertData(guid,price,size,longitude,latitude,property_type,callback){
 db.serialize(function() {
  var stmt = db.prepare("INSERT INTO casas VALUES (?,?,?,?,?,?)");
  stmt.run(guid,price,size,longitude,latitude,property_type);
 },function(){
    callback();
 });
}

The issue is that async.forEach always iterates over the JSON and each iteration doesn't wait for the database to finish that query. 问题是async.forEach总是遍历JSON,每次迭代都不会等待数据库完成该查询。 The point is to get one insert by iteration, and what I'm getting is a lot of queries stacked at the end of the execution. 关键是通过迭代获得一个插入,而我得到的是在执行结束时堆叠的大量查询。 Any help will be appreciated. 任何帮助将不胜感激。 Thank you 谢谢

Count the number of operations and when there's nothing left to do , invoke the next callback. 计算操作次数, 当没有剩下要做的时候 ,调用下一个回调。

// Get a count of the number of objects
var remaining = require(JSONfile).length;

async.forEach(JSONfile, function(item, next) {
    insertData(
            item.guid,
            item.size,
            item.price,
            item.latitude,
            item.longitude,
            item.property_type, function () {
                // only invoke callback if it's the last time in the loop
                if (!--remaining) next()
            });
    //code after the insert into db
});

This is a common pattern in node.js for handling asynchronous loops. 这是node.js中用于处理异步循环的常见模式。 Each time you think it's time to call next, just decrement the remaining number of items. 每次您认为该打电话给下一个时,只需减少剩余的项目数即可。 It will will reach zero asynchronously and the very last insertion to complete (regardless of the order they were called) will invoke the callback. 它将异步到达零,最后一个完成的插入(无论它们被调用的顺序如何)都将调用回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM