简体   繁体   中英

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. 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. You have to use await operator to wait for its promise.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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