[英]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.