How to promisify a braintree method?

2019-09-06 14:14发布

问题:

I'm having trouble promisifying a braintree method. Specifically, gateway.transaction.sale. https://developers.braintreepayments.com/reference/request/transaction/sale/node

I am using node.js with the bluebird library for promisification.

    ...
    var sale = bluebird.promisify(gateway.transaction.sale);
    return sale({
        amount: '10.00',
        paymentMethodNonce: nonce,
    });
})
.then( // doesn't reach here)
.catch(// logs out error)

Specifically, the .catch block at the bottom of the promise chain logs out:

[TypeError: this.create is not a function]

When not attempting to promisify, the code works fine.

gateway.transaction.sale({
    amount: '10.00',
    paymentMethodNonce: nonce,
}, function(err, result) {
    ... no errors, everything works fine
}

Is this a problem with how the braintree library is implemented? Am I promisifying wrong? Are there any alternative promisification strategies I can try so I can avoid callback hell?

回答1:

You're missing the context parameter, aka this. If you're using bluebird v2, do this:

var sale = bluebird.promisify(gateway.transaction.sale, gateway.transaction);

If you use version 3, do this:

var sale = bluebird.promisify(gateway.transaction.sale, {context: gateway.transaction});

You can see this in Bluebird's docs.



回答2:

You can promisify most of the braintree methods like this:

var G = {};
for(var k1 in gateway){
    if(gateway.hasOwnProperty(k1) && typeof gateway[k1] === 'object'){
        G[k1] = G[k1] || {};
        for(var k2 in gateway[k1]){
            if(typeof gateway[k1][k2] === 'function'){
                console.log('Promisify:', k1, k2);
                G[k1][k2] = G[k1][k2] || {};
                G[k1][k2] = bluebird.promisify(gateway[k1][k2], {context: gateway[k1]});

            }
        }
    }

}

Then you can use them this way:

G.paymentMethod.find('payment_method_token').then(cb_suc).catch(cb_fail);