为什么这些异步/等待调用无法正常工作?

时间:2019-01-25 03:33:51

标签: node.js express asynchronous async-await stripe-payments

请帮助!!在createPayment()和条带API Charges.create()中执行两个等待调用的过程中,执行是随机执行的,未按预期的顺序进行。我的代码进入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!'}
}

}

1 个答案:

答案 0 :(得分:2)

两个问题都在createPayment

  1. 您需要await User.updateOne调用,因为这也是异步的
  2. 如果未找到customer,则仍然需要返回一个对象,否则您的解构将引发错误。