首页 > 解决方案 > 如何从异步函数中获取数据并将其用作另一个异步函数上 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. 

标签: javascriptnode.js

解决方案


因为你getPaymentMethodId()是一个异步函数。您必须使用 await 运算符来等待它的承诺。

const payment_method = await getPaymentMethodId();
payment_method: payment_method;

推荐阅读