简体   繁体   English

如何从异步 function 获取数据并将其用作另一个异步 function 上的 json 的属性值?

[英]How to get the data from a async function and used that as a property value for a json on another asyn function?

Hi I'm new in using nodejs and haven't used javascript for a long time but i'm having a hard time getting a data from async function since I'm not getting any data when i try to use that to another async function, how would i do this without me causing so much confusion inside my project.嗨,我是使用 nodejs 的新手,并且很长时间没有使用 javascript 但是我很难从异步 function 获取数据,因为当我尝试将其用于另一个异步 ZC1C1145268E68A347 时我没有得到任何数据,如果我不会在我的项目中造成如此多的混乱,我将如何做到这一点。 Thank you in advance.先感谢您。

router路由器

 //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. 

Since your getPaymentMethodId() is an async function.由于您的getPaymentMethodId()是异步 function。 You have to use await operator to wait for its promise.您必须使用 await 运算符来等待它的 promise。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM