我是新来的,对我而言,如果一个函数只能有一个参数,那感觉就像一个承诺。在许多情况下,这让我非常沮丧。
我应该如何使用promises(简化示例)来处理以下案例
/**
* @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);
});
});