2017-03-25 27 views
0

這顆流星代碼是給誤差內的回調:使用Meteor.wrapAsync包裝的方法

Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.

我試圖Meteor.bindEnvironment爲無濟於事,想嘗試Meteor.wrapAsync。我不知道從docs。有人可以幫助我的語法嗎? THX

Meteor.methods({ 
'createTransaction': 
    function (nonceFromTheClient, Payment) { 
     let user = Meteor.user(); 
     gateway.transaction.sale(
     { 
      arg_object 
     }, 
      function (err, success) { 
      if (!err) { 
       //do stuff here 
      } 
      } 

    ); 
    } 
}); 

回答

0

裹在Meteor.wrapAsync

Meteor.methods({ 
'createTransaction': 
    function (nonceFromTheClient, Payment) { 
     this.unblock(); 
     let user = Meteor.user(); 
     var sale = Meteor.wrapAsync(gateway.transaction.sale); 
     var res = sale({arg_object}); 
     future.return(res); 
     return future.wait(); 
    } 
}); 

或者嘗試它包裹在纖維

var Fiber = Npm.require('fibers'); 
Meteor.methods({ 
'createTransaction': function (nonceFromTheClient, Payment) { 
    Fiber(function() { 
     let user = Meteor.user(); 
     gateway.transaction.sale(
     { 
      arg_object 
     }, 
      function (err, success) { 
      if (!err) { 
       //do stuff here 
      } 
      } 
    ); 
    }).run() 
    } 
}); 

更新:這是我如何處理與條紋和Async.runSync Meteor.bindEnvironment

var stripe = require("stripe")(Meteor.settings.private.StripeKeys.secretKey); 

Meteor.methods({ 
    'stripeToken': function() { 
     this.unblock(); 
     var future = new Future(); 
     var encrypted = CryptoJS.AES.encrypt(Meteor.userId(), userIdEncryptionToken); 
     future.return(encrypted.toString()); 
     return future.wait(); 
    }, 
    'stripePayment': function(token) { 
     var userId = Meteor.userId(); 
     var totalPrice = 0; 
     //calculate total price from collection 
     totalPrice = Math.ceil(totalPrice * 100)/100; 
     userEmail = Meteor.users.findOne({ 
      '_id': userId 
     }).emails[0].address; 

     // Create a charge: this will charge the user's card 
     var now = new Date(); 
     Async.runSync(function(done) { 
      var charge = stripe.charges.create({ 
       amount: Math.ceil(totalPrice * 100), // Amount in cents // coverting dollars to cents 
       currency: "usd", 
       source: token, 
       receipt_email: userEmail, 
       description: "Charging" 
      }, Meteor.bindEnvironment(function(err, charge) { 
       if (err) { 
        //handle errors with a switch case for different errors  
        done(); 
       } else { 
        //handle res, update order 
       } 
      })); 
     }); // Async.runSync 
    }, 
}); 
+0

在使用wrapAsync的第一個代碼塊中,'{arg_object}'是否也包含'gateway.transaction.sale'的回調?另外如何處理'未來',因爲它是未解決的變量? –

+0

我也嘗試了第二個代碼塊,但仍然得到相同的錯誤。 –

+0

'arg_object'不包含回調,因爲你在異步封裝它。您可以像使用回調的常規方法一樣處理方法返回。 'Meteor.call('createTransaction',nonce,payment,function(err,res){...})' – mutdmour