如何在Promise完成后执行一个函数?

时间:2017-12-17 17:49:44

标签: javascript jquery html promise stripe-payments

问题:

我只想在收费成功的情况下对我的数据库进行更改。

目前情况并非如此。在费用处理完成之前触发ARef.push(object)

我的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})
    );
});

2 个答案:

答案 0 :(得分:3)

在这些方面:

.then(
    // this happens regardless of the success of the charge
    ARef.push(object)
    //
)
.then (
    ARefList.push(object)
)

正在调用 ARef.push并将其返回值传递给then。这样就会在链条建立时发生,而不是在它被解决/拒绝时发生。

要将它们称为解析链的部分,请传入一个函数,而不是push的结果:

.then(() => {
    ARef.push(object)
    //
})
.then (() => {
    ARefList.push(object)
})

同样,这看起来很可疑:

.then(charge => 
    ARef.transaction(function(dbAmount){  
        if (!dbAmount) { 
          dbAmount = 0; 
        } 
        dbAmount = dbAmount + amount/100; 
        return dbAmount; 
    })
)

ARef.transaction看起来不会返回一个promise,但它确实接受了一个回调,暗示它是异步的(尽管这不是接受回调的唯一原因)。如果它没有提供承诺,您可能必须创建自己的承诺:

.then(charge =>
    new Promise((resolve, reject) => {
        ARef.transaction(function(dbAmount){
            // How do you know whether this failed? However it is,
            // ensure you call `reject` when it does.
            if (!dbAmount) { 
              dbAmount = 0; 
            } 
            dbAmount = dbAmount + amount/100; 
            resolve(dbAmount); // <== Resolve with whatever value should
                               // go to the next link in the chain
        })
    })
)

回到第一部分:

目前尚不清楚object来自哪里。如果是上面第一个then回调将获得的分辨率值,则:

.then(object => {
    ARef.push(object)
    //
})
.then (() => {
    ARefList.push(object)
})

同样,如果下一个then处理程序要接收它,then处理程序将需要返回一些东西:

.then(object => {
    ARef.push(object)
    return object;
})
.then (object => {
    ARefList.push(object)
})

那,或者将这两个处理程序结合起来:

.then(object => {
    ARef.push(object)
    ARefList.push(object)
})

答案 1 :(得分:1)

看起来你想要这样做 - 然后需要一个回调fn:

() => aRef.push(object)