我在NodeJS中编写了一个函数,它将一个字符串数组放在一个levelDB数据库中(每个字符串都是键,它的值变成连接到它自己的字符串或者已经存在于数据库中的值):
function addToDB(keys, callback) {
var added = 0;
keys.forEach(function(k) {
db.get(k, function(err, val) {
if (err) {
if (err.notFound) {
// Insert it into the database
db.put(k, k + k, function(err) {
if (err) {
throw err;
}
added += 1;
if (added == keys.length) {
return callback();
}
});
}
}
else {
// Update the database
var newVal = val + k;
db.put(k, newVal, function(err) {
if (err) {
throw err;
}
added += 1;
if (added == keys.length) {
return callback();
}
});
}
});
});
}
因此,当我使用keys = [" a," b"," c"]和空数据库调用addToDB时,LevelDB最终会使用以下密钥 - 价值对(应该如此):
"a" => "aa"
"b" => "bb"
"c" => "cc"
但是,我想在单独的密钥数组上多次调用addToDB,一个接一个。为此,我有以下代码:
var key1 = ["a", "b", "c"];
var key2 = ["f", "g", "a"];
var key3 = ["b", "z", "m"];
var keysArray = [key1, key2, key3];
function main(i) {
var keys = keysArray[i];
addToDB(keys, function() {
if (i < keysArray.length - 1) {
main(i + 1);
}
});
}
// Call the main function:
main(0);
运行上面的代码后,LevelDB数据库显示:
"a" => "aaa"
"b" => "bbb"
"c" => "cc"
"f" => "ff"
"g" => "gg"
"m" => "mm"
"z" => "zz"
我的问题是:有没有办法在不使用递归的main()函数的情况下将多个键数组插入到数据库中(前提是每个键的数组都没有重复)?