2017-03-07 200 views
0

我有查询数据并以json格式返回结果的api。如果我调用api.get中的查询并设置res.send(行)它工作正常,但我需要在不同的方法中调用相同的方法,所以我想我可以在外面编写它,并在需要时调用该方法。但结果在外面时会返回空白。NodeJs Mysql返回空结果

var customerRows[] 
app.get('/customers', function(req, res) { 
    getCustomers(); 
    res.json({ 
     customers : customerRows 
    }); 
}); 

function getCustomersQuery(callback) { 
    var customersDataQuery = mysqlConnection.query('SELECT * from customer_info', function(err, rows, fields) { 
     if (!err) { 
      if (rows) { 
       callback(null, rows); 
      } 
     } else { 
      callback(err, null); 
      console.log('Error while performing Query.'); 
     } 
    }); 
} 

function getCustomers() { 
    getCustomersQuery(function(err, result) { 
     if (err) { 
      console.log(err); 
     } else { 
      customerRows.push(result); 
      console.log(customerRows)//prints values 
     } 
    }); 
    console.log("Result : "+customerRows);//prints empty 
} 

我想要的结果设置为我的全局变量customerRows但它返回空。

+0

也许你应该知道异步函数的概念..最后的console.log将执行MySQL查询 –

回答

0

使用此代码

app.get('/customers', function(req, res) {  
    getCustomersQuery(function(err, result) { 
     if (err) { 
      console.log(err); 
     }   
     res.json({ 
      customers : result 
     }); 
    }); 
}); 

function getCustomersQuery(callback) { 
    var customersDataQuery = mysqlConnection.query('SELECT * from customer_info', function(err, rows, fields) { 
     if (!err) { 
      if (rows) { 
       callback(null, rows); 
      } 
     } else { 
      callback(err, null); 
      console.log('Error while performing Query.'); 
     } 
    }); 
} 
+0

之前被解雇我检举这个不是一个答案,因为它不是一个答案 - 这是只是一些代码。我已经看到事情少了,这是一个可以接受的答案? –