mpdc
mpdc

Reputation: 3560

Error checking a tokenize() function in a Braintree transaction

I'm getting a little confused with Promises in JavaScript, when currently trying to add some validation and error message handling to a function.

This code works:

hf.tokenize().then(function(payload) {
    // ...
}).then(function(payload) {
    // ...
}).catch(function(err) {
   console.log(err);
});

But does no real error handling, just dumps them in the console. When I try and do this:

hf.tokenize(function(err, payload) {
    if (err) {
        // Handle error
    }

    return;
}).then(function(payload) {
    // ...
}).then(function(payload) {
    // ...
}).catch(function(err) {
   console.log(err);
});

I get the following error:

Uncaught TypeError: Cannot read property 'then' of undefined at HTMLInputElement anonymous

I've looked at a few other questions that give solutions to similar error responses, but the difficulty comes in that I'm not even sure what I'm meant to be doing at this point, or what to return.

Upvotes: 1

Views: 426

Answers (1)

TheMikeInNYC
TheMikeInNYC

Reputation: 423

Javascript promises are a new syntax but js has had async before the syntax in the form of callbacks. Usually a method has overloads. If you call it without parameters then you can use the Promise syntax and if you call it with parameters then you use the old callback style (where one the the parameters is a function(){ do stuff }).

https://braintree.github.io/braintree-web/current/HostedFields.html#tokenize

callback May be used as the only parameter of the function if no options are passed in. The second argument, data, is a tokenizePayload. If no callback is provided, tokenize returns a function that resolves with a tokenizePayload.

You are mixing them and since you are calling the overload with parameters it doesn't have a return value (the void in -> {Promise|void} hence the "undefined" error.

Upvotes: 1

Related Questions