0

I'm writing a NodeJS v0.10 application with MariaSQL.

i want to create a function that returns the id of a row, and if the row doesn't exist, to create it and then return the id.

this is what I have so far:

TuxDb.prototype.createIfNEDrinkCompany = function(drinkCompany) {
 this.client.query("insert into drink_company(drink_company_name) values(:drink_company) on duplicate key update drink_company_id=drink_company_id",
    {'drink_company' : drinkCompany})
    .on('result',function(res) {
    res.on('end',function(info){
        if (info.insertId > 0) {
                return info.insertId;
        } else {
            this.client.query("select drink_company_id from drink_company where drink_company_name = :drink_company",{'drink_company' : drinkCompany})
                .on('result',function(res){
                    res.on('row',function(row){
                        return row.drink_company_id;
                    });
                });
        }
    });
    });

}

now the problem is that since it's asynchronous, the function ends before the value is returned.

how can I resolve this issue ?

4

1 回答 1

1

nodejs 处理异步代码的标准方法是提供回调函数作为方法的最后一个参数,并在异步完成时调用它。回调函数标准签名是 (err, data) - 您可以在此处阅读更多信息:了解 Javascript 和 node.js 中的回调

重写你的代码:

TuxDb.prototype.createIfNEDrinkCompany = function(drinkCompany, callback) { 
 this.client.query("insert into drink_company(drink_company_name) values(:drink_company) on duplicate key update drink_company_id=drink_company_id",
    {'drink_company' : drinkCompany})
    .on('result',function(res) {
    res.on('end',function(info){
        if (info.insertId > 0) {
                callback(null, row.drink_company_id);
        } else {
            this.client.query("select drink_company_id from drink_company where drink_company_name = :drink_company",{'drink_company' : drinkCompany})
                .on('result',function(res){
                    res.on('row',function(row){
                        callback(null, row.drink_company_id);
                    });
                });
        }
    });
    });

}

然后在代码中调用你的方法

db.createIfNEDrinkCompany(drinkCompany, function(err, id){
    // do something with id here
})
于 2015-01-08T15:15:44.333 回答