数组不会填写

时间:2014-08-29 10:12:04

标签: javascript node.js

我有一个奇怪的问题。

我从数据库中获取行并将其插入到数组中。但Array.push()无法工作。

来源

var donations_data = [];

/* Get Donations */
instance.server.db.query("SELECT * FROM `donations` WHERE `userid`='" + instance.user_data.userid + "' AND `visible`='1' ORDER BY `date` DESC LIMIT 10", function(error, rows, fields) {
    if(rows.length > 0) {
        _.each(rows, function (entry, index) {
            console.log(">>>>>>>>>>>>>>>>>>>>>");
            console.log(entry);
            console.log(">>>>>>>>>>>>>>>>>>>>>");

            donations_data.push({
                username:           entry.from_username,
                note:               entry.note,
                timestamp:          entry.date,
                amount:             entry.amount,
                currency:           entry.currency,
                currency_symbol:    '?',
                transaction_id:     entry.transaction_id,
                paypal_email:       entry.from_paypal_email
            });
        });
    }
});

console.log("==================================");
console.log(donations_data);
console.log("==================================");

输出

>>>>>>>>>>>>>>>>>>>>>
{ id: 4,
  userid: 1,
  from_username: 'user 2',
  from_paypal_email: 'demo@example.com',
  transaction_id: '12345',
  status: 'COMPLETED',
  note: 'No Message',
  date: 1386012587,
  amount: '5.00',
  cent_amount: 0,
  an_dt: '',
  currency: 'EUR',
  visible: 1,
  date2: Mon Dec 02 2013 20:29:47 GMT+0100 (CET),
  new: 0 }
>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>
{ id: 3,
  userid: 1,
  from_username: 'USer 1',
  from_paypal_email: 'demo@example.com',
  transaction_id: '23ewqs',
  status: 'COMPLETED',
  note: 'Das ist ein Test',
  date: 1386012427,
  amount: '5.00',
  cent_amount: 0,
  an_dt: '',
  currency: 'EUR',
  visible: 1,
  date2: Mon Dec 02 2013 20:27:07 GMT+0100 (CET),
  new: 0 }
>>>>>>>>>>>>>>>>>>>>>
==================================
[]
==================================

你能告诉我为什么数组不会被填满吗?数据将打印出来,因此必须正常工作......

1 个答案:

答案 0 :(得分:3)

您尝试在异步 instance.server.db.query方法有机会完成之前记录将对象添加到数组的结果。循环完成后使用回调来获取数据

var donations_data = [];

function doQuery(callback) {
  instance.server.db.query(SQL, function(error, rows, fields) {
    // add data to array with loop
    // call callback
    callback(donations_data);
  });
}

doQuery(function (donations_data) {
  console.log(donations_data);
});