javascript - 如何从异步函数中获取数据并将其用作另一个异步函数上 json 的属性值?
问题描述
嗨,我是使用 nodejs 的新手,并且很长时间没有使用 javascript,但是我很难从异步函数中获取数据,因为当我尝试将其用于另一个异步函数时我没有得到任何数据,如果我不会在我的项目中造成如此多的混乱,我将如何做到这一点。先感谢您。
路由器
//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()
是一个异步函数。您必须使用 await 运算符来等待它的承诺。
const payment_method = await getPaymentMethodId();
payment_method: payment_method;
推荐阅读
- r - 将因子转换为数据框中的变量
- reactjs - react-hook-form 访问嵌套组件中的验证规则
- python - 如何将简单的 smtp python 服务器绑定到局域网?
- php - PHP 查询未按预期工作。应显示错误时运行插入语句
- c# - 我怎样才能解决在空中跳跃的问题?
- html - 如何使用 CSS 不断淡入淡出 HTML 按钮?
- javascript - 通过复选框选择更改 svg 元素背景颜色
- c - 这是我大学 c 课上的一个练习,我似乎无法解决它,有人帮帮我
- python - 无法加载原生 TensorFlow 运行时。?
- r - 如何将一个图的边添加到 R 中的另一个图(两个图的顶点相同)?