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

问题描述 投票:1回答:2

题:

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

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

我的语法有什么问题?


码:

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})
    );
});
javascript jquery html promise stripe-payments
2个回答
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看起来并不会返回一个承诺,但它确实接受了一个回调,暗示它是异步的(尽管这不是接受回调的唯一原因)。如果它没有提供承诺,您可能必须创建自己的:

.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
投票

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

() => aRef.push(object)
© www.soinside.com 2019 - 2024. All rights reserved.