【发布时间】:2019-01-25 12:04:43
【问题描述】:
请帮忙!!在 createPayment() 和条带 API charge.create() 中的两个 await 调用执行期间,执行是随机执行的,而不是按预期的顺序执行。我的代码进入createPayment()然后又回到const {payment} = await createPayment(program, user, toUser, paymentToken);然后又进入createPayment(),没有意义!!!
exports.subscribeToProgram = async function(req,res){
try {
const {paymentToken, program} = req.body;
const user = res.locals.user;
//Find program to be subscribed
const foundProgram = await Program.findOne({_id: program._id}).populate('user').exec();
const toUser = foundProgram.user.id;
if(toUser === user.id)
{
return res.status(422).send({errors: [{title: 'Invalid User!', detail: 'You can\'t subscribe to your own program!'}]})
}
// Create Payment
// THIS PART IS NOT WORKING PROPERLY!!!!
const {payment} = await createPayment(program, user, toUser, paymentToken);
const charge = await stripe.charges.create({
amount: foundProgram.price * 100 * CUSTOMER_SHARE,
currency: 'usd',
description: 'Example charge',
source: payment.tokenId,
});
//If payment was created successfully
if(payment && charge)
{
//Create subscription
//Save created subscription
//Append a booking to bookings array
}else{
return res.status(422).send({errors: [{title: 'Payment declined!', detail: err }]})
}
} catch (err) {
console.log(err)
return res.status(422).send(err);
}
}
CreatePayment()
async function createPayment(program, user, toUser, token){
//Get user from booking
const userToCharge = user;
//Create customer from stripe serices
const customer = await stripe.customers.create({
source: token.id,
email: userToCharge.email
});
//If custome exist
if(customer)
{
//Update user
User.updateOne({_id: userToCharge.id}, {$set: {stripeCustomerId: customer.id}}, () => {});
//Create Payment
const payment = new Payment({
fromUser: userToCharge,
toUser, //Destructurize value
fromStripeCustomerId: customer.id,
program,
tokenId: token.id,
amount: program.price * 100 * CUSTOMER_SHARE // 80% of value if for
});
//Save payment
try
{
const savedPayment = await payment.save();
return {payment: savedPayment}
}
catch (error)
{
return {err: err.message};
}
}else{
return { err: 'Cannot process Payment!'}
}
}
【问题讨论】:
-
createPayment()是否返回承诺?stripe.charges.create()是否返回承诺? -
您为什么将
await与createPayment()一起使用?await仅在您根据承诺调用它时才会做一些有用的事情。如果createPayment()中有异步内容,那么您需要修复它以返回当这些异步内容完成时解决的承诺。 -
您与
createPayment()的问题是How do I Return the Response from an Asynchronous Call 的重复 -
阅读 jfriend00 引用的帖子:How do I return the response from an asynchronous call?。然后阅读this 和this。冲洗并根据需要重复:)
-
@jfriend00
createPayment是async意味着它将隐式返回一个 Promise,不需要显式返回。该问题似乎还有另一个未等待的异步调用 (User.updateOne)。
标签: node.js express asynchronous async-await stripe-payments