【问题标题】:Execute rest of the function after async function is finished在异步函数完成后执行其余的函数
【发布时间】:2019-12-01 22:20:44
【问题描述】:

我想使用 Stripe 检索付款的最后 4 位数字。为此,我必须运行一个异步函数,并在该函数内运行另一个异步函数。 之后我想用最后 4 个数字更新数据库。但我想在解决这两个函数后更新数据库,如果没有得到undefined

if (intent.status === "succeeded") {
    const user = res.locals.decodedClaims;
    const uid = user.uid;
    let last4; //trying to set last4 to global var so that i can change it inside a function

    // The payment didn’t need any additional actions and completed!
    // Handle post-payment fulfillment

    //get payment last4 digits
    stripe.paymentIntents.retrieve(intent.id, function(err, paymentIntent) {
      // asynchronously called
      if (err) {
        return console.log("PI retrieve error: ", err);
      }
      stripe.charges.retrieve(paymentIntent.charges.data[0].id, function(
        err,
        charge
      ) {
        if (err) {
          return console.log("Charge retrieve error: ", err);
        }
        last4 = charge.payment_method_details.card.last4;
        console.log("charge: ", last4); // works, eg: 4242
      });
    });

    //update status in database
    const userRef = db.collection("users").doc(uid);
    let updatedStatus = userRef.update({
      paid: true,
      last4: last4 //undefined
    });

    updatedStatus.catch(err => {
      console.log(err);
    });
    //send success message to client
    return {
      success: true,
      hello: 1
    };

预期结果:

//update status in database
    const userRef = db.collection("users").doc(uid);
    let updatedStatus = userRef.update({
      paid: true,
      last4: last4 //undefined
    });

    updatedStatus.catch(err => {
      console.log(err);
    });
    //send success message to client
    return {
      success: true,
      hello: 1

所有这一切都在我得到 last4 的值之后运行。

【问题讨论】:

    标签: javascript node.js asynchronous google-cloud-firestore stripe-payments


    【解决方案1】:

    你在这里错过了 JS 最重要的部分。 Javascript是异步的。因此,当您的代码通过这 2 个异步调用时,您的 userRef.update() 也会同时被调用。这就是为什么你变得不确定。此外,如果这一切都发生在函数内部,你的回报并不能真正帮助你。它总是会返回成功,因为它是异步工​​作的。

    查看下面的代码。您需要返回一个 Promise,以便您的函数等待所有异步函数返回响应。

    yourFunction() {
    return new Promise ( function(resolve, reject) {
    if (intent.status === "succeeded") {
        const user = res.locals.decodedClaims;
        const uid = user.uid;
        let last4; //trying to set last4 to global var so that i can change it inside a function
    
        // The payment didn’t need any additional actions and completed!
        // Handle post-payment fulfillment
    
        //get payment last4 digits
        stripe.paymentIntents.retrieve(intent.id, function(err, paymentIntent) {
          // asynchronously called
          if (err) {
            reject(err);
         }
          stripe.charges.retrieve(paymentIntent.charges.data[0].id, function(
            err,
            charge
          ) {
            if (err) {
              reject(err);
            }
            last4 = charge.payment_method_details.card.last4;
            console.log("charge: ", last4); // works, eg: 4242
            //update status in database
            const userRef = db.collection("users").doc(uid);
            let updatedStatus = userRef.update({
              paid: true,
              last4: last4 //undefined
            });
    
            updatedStatus.catch(err => {
              reject(err);
            });
            //send success message to client
            resolve({
              success: true,
              hello: 1
            });
          });
        });
    
    
    });
    
    

    在此之后,您可以像这样调用您的函数

    myFunction().then(function(success) {
       // your {success: true, hello: 1} comes here
    }).catch(function(err)) {
       // all the errors come here.
    }
    

    如果您想改用 async/await,只需定义您的 main 函数,使其 async functionName() {}. 然后,执行以下操作:

    try {
      selectedPlan = await Stripe.plans.retrieve(stripePlanId); // use stripe's functions here.
    } catch (error) {
      // error handling
    }
    

    【讨论】:

    • 不能这样做,因为我在该函数中有很多 if else 语句,我不想​​把它搞砸。有没有办法让我只在上面提到的 if 语句中让它异步等待?
    • 在这种情况下,您可以对所有调用执行异步/等待。然后,您的所有代码都应该没问题。
    猜你喜欢
    • 2015-12-06
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多