简体   繁体   English

如何从嵌套函数中检索值

[英]How to retrieve value from within nested function

I started learning javascript a couple weeks ago but I think I might have skipped a chapter or two..几周前我开始学习 JavaScript,但我想我可能跳过了一两章。

exports.createStripeCustomer = functions.https.onCall(async (data, context) => {

    // Create stripe customer
    await stripe.customers.create({
        email: context.auth.token.email,
        payment_method: data,
        invoice_settings: {
            default_payment_method: data,
        },
    }, function (err, customer) {

        if (!err) {

            // Attempt to create subscription
            stripe.subscriptions.create({
                customer: customer.id,
                items: [
                    {
                        plan: 'plan_GKCHNvZX2SVc8y',
                    },
                ],
                expand: ['latest_invoice.payment_intent'],
            }, function (err, subscription) {

                if (!err) {

                    return console.log(subscription.latest_invoice.payment_intent.status);

                }

            });
        }

    });

});

Those are my nested functions, triggered by an https call.这些是我的嵌套函数,由 https 调用触发。 On the deepest level I am logging the value I want, to the console.在最深层次上,我正在将我想要的值记录到控制台。

return console.log(subscription.latest_invoice.payment_intent.status);

How can I take that value and move it up so I can send it back to the client as result of the https call?如何获取该值并将其向上移动,以便我可以将其作为 https 调用的结果发送回客户端?

The code you've provided above uses callbacks to exchange information in a one-directional way.您在上面提供的代码使用回调以单向方式交换信息。 To make use of callable functions properly, you must return a resolved or rejected promise so that data can be passed back through the chain.要正确使用可调用函数,您必须返回已解决或已拒绝的承诺,以便数据可以通过链传回。

Recommended reading:JavaScript Promises: an Introduction推荐阅读:JavaScript Promises: an Introduction

You can either wrap your code above in a Promise;您可以将上面的代码包装在 Promise 中; or better yet you can switch to using the promises provided by the stripe-node SDK.或者更好的是,您可以切换到使用条带节点SDK 提供的承诺。

Changing your code to using chained Promises results in:将代码更改为使用链式 Promise 会导致:

exports.createStripeCustomer = functions.https.onCall(async (data, context) => {
    // Create stripe customer
    await stripe.customers.create({
        email: context.auth.token.email,
        payment_method: data,
        invoice_settings: {
            default_payment_method: data,
        },
    })
    .then((customer) => {
      // Attempt to create subscription
      return stripe.subscriptions.create({
          customer: customer.id,
          items: [
              {
                  plan: 'plan_GKCHNvZX2SVc8y',
              },
          ],
          expand: ['latest_invoice.payment_intent'],
      });, function (err, subscription) {
    })
    .then((subscription) => {
        return subscription.latest_invoice.payment_intent.status;
    })
    .catch((err) => {
        console.log('An error occured:', err);
        // see https://firebase.google.com/docs/functions/callable#handle_errors
        throw new functions.https.HttpsError('unexpected-error', 'Unexpected error');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM