【问题标题】:Why these async/await calls are not working properly?为什么这些 async/await 调用不能正常工作?
【发布时间】: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() 是否返回承诺?
  • 您为什么将awaitcreatePayment() 一起使用? await 仅在您根据承诺调用它时才会做一些有用的事情。如果 createPayment() 中有异步内容,那么您需要修复它以返回当这些异步内容完成时解决的承诺。
  • 您与createPayment() 的问题是How do I Return the Response from an Asynchronous Call 的重复
  • 阅读 jfriend00 引用的帖子:How do I return the response from an asynchronous call?。然后阅读thisthis。冲洗并根据需要重复:)
  • @jfriend00 createPaymentasync 意味着它将隐式返回一个 Promise,不需要显式返回。该问题似乎还有另一个未等待的异步调用 (User.updateOne)。

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


【解决方案1】:

两个问题,都在createPayment

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

【讨论】:

  • 非常感谢您的回答。这是我第三次编写异步代码,所以我还是习惯了。我会按照你的建议更新我的代码。谢谢:)
  • @RodrigoVillalobos 没问题,不确定您是否编辑了createPayment,或者它被代码溢出隐藏了,但我看到您正在返回一个对象。 2.
  • 你说得对,James,我在 createPayment 中错过了一个 await 调用,我还添加了一个额外的 await 调用,用于在同一个函数中向用户收费,它运行良好!还要感谢@paulsm4 发布的资源,我能够理解发生了什么
猜你喜欢
  • 1970-01-01
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多