Sunday, 11 June 2017

How do I pass the original request in a callback function?

I'm trying to avoid callback hell by naming functions, but am unable to request pass an object that is not part of the original ?scope? of the parent method.

Here's the working code I'm trying to optimize:

//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');
}

When I try to modularize my code, I'm unsure on how to pass the req object, since the charge.create method is something I didn't make, so I can't make it accept any other arguments:

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

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



via koleslaw

No comments:

Post a Comment