0

I'm new to promise and to me it feels like a promise if a function that can only have 1 argument. And in many case it makes me very frustrated.

How am I supposed to handle cases such as the following with promises (simplified example)

/**
 * @api {post} /payments Create a new payment
 *
 * @apiParam {String} uuid uuid of the user.
 * @apiParam {String} status the payment status
 * @apiParam {String} transactionId Id of the transaction
 * @apiParam {String} creationDate The payment date
 * @apiParam {Number} productId The product Id
 */
router.post('/', function(req, res, next) {
  const userUUID = req.body.userUUID;
  const productId = req.body.productId;

  models.account.findOne({ where: { userUUID }})
    .then(account => {
        //Here I check if the accountId is correct
        if (!account) throw new errors.NotFound('unknown userUUID')
        return account;
    }).then(existingAccount)
        //Here I check if the productId is correct
        return models.product.findOne({ where: { productId }}).then(product => {
            if (!product) throw new errors.NotFound('unknown productId')
            return product;
        })
    })
    .then(existingProduct => {
        //Here I insert the payment in database
        return models.payment.create({
            productId,
            userUUID,
            existingProduct.price
        })
    })
    .then(existingPayment => {
        //My Problem :
        //Here, for example, I need : 
        //   existingProduct
        //   existingAccount
        //   existingPayment
        //How can I access them ???
    })
    .then(s => res.json(s))
    .catch(error => {
      if (error instanceof errors.NotFound)
        return res.status(404).send(error.message);
      return next(error);
    });
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
IggY
  • 3,005
  • 4
  • 29
  • 54
  • 1
    Just resolve with a composite type like object or array –  Aug 04 '16 at 09:26
  • I never saw anyone doing this in any source code I've looked at. Isn't this method 'dirty' ? – IggY Aug 04 '16 at 09:28
  • @IggY Composite objects, and especially arrays, are very common as promise results. It gets even more trivial in ES6 with shorthand object initialisers and parameter destructuring. There are other approaches as well, though, see the duplicate. – Bergi Aug 04 '16 at 09:32

0 Answers0