2017-05-09 52 views
1

如何等待Braintree Transaction.search()函數返回所有數據。 現在它不會等待,並返回未定義的返回值。 這裏是代碼 我試圖使用Meteor.asynwrap,但這也行不通。 `Braintree Transaction.search在流星服務器

function getTrxns(cid) { 
    var future = new Future(); 
    var trxns = []; 
    var i = 0 
    var stream = gateway.transaction.search(function (search) { 
         r =  search.customerId().is(cid)}); 

    stream.on("data", function(data){ 
     i = i+1 
     trxns.push({ 
     'id':data.id, 
     'amount':data.amount, 
     'crtDt': data.createdAt, 
     'ccType': data.creditCard.cardType, 
     'currency': data.currencyIsoCode, 
     'last4': data.creditCard.last4, 
     'expdt': data.creditCard.expirationDate 
     }); 
}); 
stream.on("end", function(){ 
    // print the output in console 
    console.log('End Stream cnt: '+i); 
    return trxns; 
}); 

stream.resume(); 
} 

Meteor.methods({ 
findCustTrxns: function() { 
     var btId = Meteor.user().custBtId;  
     if (!btId) { return []; }; 
     console.log('findCustTrxns cusBtId: '+btId); 
     var xx = getTrxns(btId); 
       console.log('xx len :'+xx.length); 
} 

}); 


OUTPUT is: 

I20170509-15:22:09.095(0)?  findCustTrxns cusBtId: 232057823 
I20170509-15:22:09.095(0)?  Exception while invoking method 'findCustTrxns' TypeError: Cannot read property 'length' of undefined 
I20170509-15:22:09.095(0)?  End Stream cnt: 56 

+0

您正在使用哪個版本的Meteor? – DSK

回答

0

找到了一種方法,使其工作: 1.增加了一個回調函數
功能getTrxns(CID,回調
2.調用回調在stream.on('end; ..)這裏是代碼

  function getTrxns(cid,callback) { 

     var trxns = []; 
     var i = 0 
     var stream = gateway.transaction.search(function (search) { 
          r =  search.customerId().is(cid)}); 

     stream.on("data", function(data){ 
      i = i+1 
      trxns.push({ 
       'id':data.id, 
      }); 
    }); 
    stream.on("end", function(){ 
     // print the output in console 
     console.log('End Stream cnt: '+i); 
     callback('', trxns); 
    }); 

    stream.resume(); 
    } 



3. Changed the Meteor Method : 

findCustTrxns: function(btId) { 


     if (!btId) { return []; }; 
     console.log('findCustTrxns cusBtId: '+btId); 

var trxns = []; 
    var i = 0; 

     var fn = Meteor.wrapAsync(getTrxns); //made it a synchronous call 
     try { 
      var res = fn(btId); 
      if (res) { 
       console.log('Got data from getTrxns '); 
       return res; 
      } 
     } catch(err) { 
       console.log('Error calling hetTrxns '+err); 
     } 
}, //findCustTrxns 

現在我能夠獲得交易。希望它有幫助