![](/img/trans.png)
[英]JavaScript: how to return a value from a asyn function in a for loop
[英]How to get the data from a async function and used that as a property value for a json on another asyn function?
嗨,我是使用 nodejs 的新手,並且很長時間沒有使用 javascript 但是我很難從異步 function 獲取數據,因為當我嘗試將其用於另一個異步 ZC1C1145268E68A347 時我沒有得到任何數據,如果我不會在我的項目中造成如此多的混亂,我將如何做到這一點。 先感謝您。
路由器
//this function is located inside a router and i want to use the output as a property value for a json.
const createPaymentMethod = async () => {
return paymongo.paymentMethods.create({
data: {
attributes: {
type: 'card',
details: {
card_number: card,
exp_month: mo,
exp_year: yr,
cvc: cvc,
}
}
}
},
)
.then(paymentMethods => {
return paymentMethods.data.id;
})
.catch(err => {
return err;
});
}
const getPaymentMethodId = async () => {
var id = await createPaymentMethod();
console.log(id);
}
//Attaching Payment Method to Intent
const attachPaymentIntent = async () => {
return paymongo.paymentIntents.attach(getPaymentIntentId(),{
data: {
attributes: {
payment_method: getPaymentMethodId()
}
}
})
.then(attachPaymentIntent => {
return attachPaymentIntent;
})
.catch(err => {
return err;
});
}
const getAttachedPaymentIntent = async () => {
var id = await attachPaymentIntent();
console.log(id);
}
getAttachedPaymentIntent();
//but after all this trouble the API still saying that the 'payment_method:' inside the attachPaymentIntent is still empty.
由於您的getPaymentMethodId()
是異步 function。 您必須使用 await 運算符來等待它的 promise。
const payment_method = await getPaymentMethodId();
payment_method: payment_method;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.