javascript
  • node.js
  • 2014-08-29 59 views 0 likes 
    0

    我有一个好奇的问题。Array will not fill out

    我从数据库中提取行并将其插入数组。但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: '[email protected]', 
        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: '[email protected]', 
        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 } 
    >>>>>>>>>>>>>>>>>>>>> 
    ================================== 
    [] 
    ================================== 
    

    你能告诉我为什么阵列就不会成交?数据将打印出来,因此必须工作...

    +0

    好吧,我明白了,但我如何检查查询是否完成? – 2014-08-29 10:15:46

    回答

    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); 
    }); 
    
    相关问题