How to execute a function only once a Promise is done?

0

QUESTION:

I would like to make changes to my database only if the charge was successful.

That is currently not the case. ARef.push(object) is triggered before the charge is done processing.

What is wrong in my synatx ?


CODE:

router.post("/", (req, res) => {

    var amount = req.body.amount;
    var object;
    var ARef = admin.database().ref("ref");
    var ARefList;
    amount = amount * 100; 

    var object = {
        amount: amount,
        email: email,
        inversedTimeStamp: now
    }

    stripe.customers.create({
        email: req.body.stripeEmail,
        source: req.body.stripeToken
    })
    .then(customer =>
        stripe.charges.create({
            amount: amount,
            description: "desc",
            currency: "usd",
            customer: customer.id
        })
    )
    .then(charge => 
        ARef.transaction(function(dbAmount){  
            if (!dbAmount) { 
              dbAmount = 0; 
            } 
            dbAmount = dbAmount + amount/100; 
            return dbAmount; 
        })
    )
    .then(
        // this happens regardless of the success of the charge
        ARef.push(object)
        //
    )
    .then (
        ARefList.push(object)
    )
    .then(
        res.render("received",{amount:amount/100})
    );
});

Link: How to execute a function only once a Promise is done?
Source: Stack Jquery

Share.

About Author

Leave A Reply