繁体   English   中英

如何从嵌套函数中检索值

[英]How to retrieve value from within nested function

几周前我开始学习 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);

                }

            });
        }

    });

});

这些是我的嵌套函数,由 https 调用触发。 在最深层次上,我正在将我想要的值记录到控制台。

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

如何获取该值并将其向上移动,以便我可以将其作为 https 调用的结果发送回客户端?

您在上面提供的代码使用回调以单向方式交换信息。 要正确使用可调用函数,您必须返回已解决或已拒绝的承诺,以便数据可以通过链传回。

推荐阅读:JavaScript Promises: an Introduction

您可以将上面的代码包装在 Promise 中; 或者更好的是,您可以切换到使用条带节点SDK 提供的承诺。

将代码更改为使用链式 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