从sqlite3调用的错误通知调用者有关node.js中回调的错误

时间:2014-03-17 10:14:07

标签: node.js sqlite callback

在node.js + sqlite3中:

通过回调通知调用者有关错误并让调用者再次尝试的好方法是什么?当我们得到数据库锁定错误时 - 想尝试再次运行查询。

TestController.prototype.addDevices = function (number_of_devices, callback_after_all_devices_have_been_added) {
    var controller = this;
    var db = controller.connectToDb();

    for(i = 0; i < number_of_devices; i++) {
        db.each("SELECT api_key as ak FROM user_table ORDER BY RANDOM() LIMIT 1", function(err, row) {
            //sometimes we get a SQLITE: database locked error
            if (err !== null) {
                console.log("Error found");
                //i-- this will not work - but how do we do it then?
                return;
            }
            console.log("Error: " + err);
            //code to process if we get an entry from the user_table ..
        });
    }
}

1 个答案:

答案 0 :(得分:0)

这就是我设法解决这个问题的方法 - 添加了一个重试计数器并将问题代码移动到它自己的函数中,将结尾作为回调传递。它有效 - 但这是一个好方法吗? (除了使用promises或异步模块?)

TestController.prototype.addDevices = function (number_of_devices, callback_after_all_devices_have_been_added) {
    var number_of_users = 0;
    var controller = this;
    controller.pending_db_writes_for_device = number_of_devices;

    for(i = 0; i < number_of_devices; i++) {
        var api_key = controller.getRandomAPIKeyFromDB(10,function(access_key) {
            var mac_address = controller.generateRandomMAC();
            var friendly_name = Faker.random.array_element(["Washing Machine","Television","Dishwasher","Set top box"]);
            var description = Faker.Lorem.sentence(5);
            controller.registerDeviceWithAPI(mac_address, friendly_name, description, access_key, callback_after_all_devices_have_been_added);
        });
    }
}

TestController.prototype.getRandomAPIKeyFromDB = function (retry_counter, callback) {
  var controller = this;
  var db = controller.connectToDb();
  console.log("Retry counter: "+ retry_counter);
  db.each("SELECT api_key as ak FROM user_table ORDER BY RANDOM() LIMIT 1", function(err, row) {
            if (err !== null) {
                console.log("Error: " + err + "retry count: "+ retry_counter);
                console.log("Error found");
                if(retry_counter === 0) {
                    console.log("Bailing out after retry limit reached");
                    return;
                }
                controller.getRandomAPIKeyFromDB(--retry_counter,callback);
            }
            else {
                console.log("Successfully got api key: " + row.ak);
                callback(row.ak);
            }
        }
    );
}