Node.js 用于在SQLite中插入数据值的同步循环
我正在使用Node.js 用于在SQLite中插入数据值的同步循环,node.js,sqlite,synchronization,sequelize.js,Node.js,Sqlite,Synchronization,Sequelize.js,我正在使用sequelezer将值插入本地数据库。它是一种需要在服务器上第一次运行的安装脚本 由于nodejs“异步”函数调用,我的sqlite数据库被锁定,我得到以下错误 未处理的拒绝SequelizeTimeoutError:SQLITE\u BUSY:数据库已锁定 这是我的密码 var country_json = { "AF": "Afghanistan", "AX": "\u00c5land Islands", "AL": "Albania
sequelezer
将值插入本地数据库。它是一种需要在服务器上第一次运行的安装脚本
由于nodejs“异步”函数调用,我的sqlite数据库被锁定,我得到以下错误
未处理的拒绝SequelizeTimeoutError:SQLITE\u BUSY:数据库已锁定
这是我的密码
var country_json = {
"AF": "Afghanistan",
"AX": "\u00c5land Islands",
"AL": "Albania",
//........
"ZW": "Zimbabwe"
};
for (key in country_json) {
console.log("ABUZAR");
console.log(key.toString('utf8') + " " + country_json[key].toString('utf8'));
db.country_name.findOrCreate({
where: {
country_iso: key.toString('utf8')
},
defaults: {
country_name: country_json[key].toString('utf8')
}
})
.spread(function(country, created) {
console.log(country.get({
plain: true
}));
console.log(created);
});
}
我尝试了几个同步npm模块,但每个模块似乎都能正常工作。只是想知道如何在node js中处理这些场景。您可以将异步函数与循环、逻辑、递归等混合使用-它将以同步方式逐个执行所有步骤。下面是说明的脚本:
global.SynJS = global.SynJS || require('synjs');
var Sequelize = require('sequelize');
var db = new Sequelize('tracker', 'tracker', 'tracker123', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
function insertWrapper(db,context,key,value) { // <- wrapper function that returns initially incomplete result
var res = {done: false};
db.query("select CONCAT(?,'--->',?)", { replacements: [key,value], type: db.QueryTypes.SELECT })
.spread(function(row) {
console.log('done: row=',row);
res.done = true;
SynJS.resume(context); // once result is ready, it notifies context of caller function to continue
});
return res;
}
function myFunc(modules,db, country_json) { // <- function that is run via SynJS
for (var key in country_json) {
var res = modules.insertWrapper(db,_synjsContext,key,country_json[key]);
SynJS.wait(res.done); // <-- wait for the callback to finish
}
};
var modules = { // <-- convenience object to pass whatever myFunc may need, as it cannot access closures
insertWrapper: insertWrapper,
};
var country_json = {
"AF": "Afghanistan",
"AX": "\u00c5land Islands",
"AL": "Albania",
//........
"ZW": "Zimbabwe"
};
// run myFunc via SynJS
SynJS.run(myFunc,null,modules,db,country_json,function () {
db.close();
console.log('done');
});
Executing (default): select CONCAT('AF','--->','Afghanistan')
done: row= { 'CONCAT(\'AF\',\'--->\',\'Afghanistan\')': 'AF--->Afghanistan' }
Executing (default): select CONCAT('AX','--->','Ã…land Islands')
done: row= { 'CONCAT(\'AX\',\'--->\',\'Ã…land Islands\')': 'AX--->Ã…land Islands' }
Executing (default): select CONCAT('AL','--->','Albania')
done: row= { 'CONCAT(\'AL\',\'--->\',\'Albania\')': 'AL--->Albania' }
Executing (default): select CONCAT('ZW','--->','Zimbabwe')
done: row= { 'CONCAT(\'ZW\',\'--->\',\'Zimbabwe\')': 'ZW--->Zimbabwe' }
done