【问题标题】:How do I pass the original request in a callback function?如何在回调函数中传递原始请求?
【发布时间】:2017-06-11 19:46:23
【问题描述】:

我试图通过命名函数来避免回调地狱,但无法请求传递不属于原始 ?scope 的对象?父方法。

这是我正在尝试优化的工作代码:

//req exists, as this is inside an Express route handler 
charge.create({
    amount: req.body.amount
    //...
}, function(err, createdCharge) {
      console.log('Purchased: '+req.body.product);
      res.send('Success');
}

当我尝试模块化我的代码时,我不确定如何传递 req 对象,因为 charge.create 方法是我没有创建的,所以我不能让它接受任何其他参数:

charge.create({
   amount: req.body.amount
   //...
}, confirmCharge);

function confirmCharge(err, createdCharge) {
      console.log('Purchased: '+req.body.product); //req doesn't exist!
}

【问题讨论】:

    标签: node.js callback request


    【解决方案1】:
    charge.create({
       amount: req.body.amount
       //...
    }, confirmCharge(req));
    
    function confirmCharge(req) {
          console.log('Purchased: '+req.body.product); //req exists!
    }
    

    【讨论】:

    • charge.create 返回 err 和 createdCharge,调用 confirmCharge 时不需要指定。当我输入 confirmCharge(req) 时,它说 Unknown arguments。
    • 如果您需要特定的现成工作解决方案,您需要发布收费代码。
    • 这是我使用表单 Stripe 的示例。 stripe.com/docs/charges`var token = request.body.stripeToken; // 使用 Express // 对用户的卡进行充值: var charge = stripe.charges.create({ amount: 1000, currency: "usd", description: "Example charge", source: token, }, function(err, charge) { // 异步调用 });`
    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多