1

I have a stripe Object that I am working with in jQuery.

A property of my object is a function to get a stripe token.

getStripeToken : function(){
    stripeOb.stripe.createToken(stripeOb.stripeCard).then(function(result) {
        if (result.error) {
          // Inform the user if there was an error
          var errorElement = document.getElementById('card-errors');
          return result.error.message; //errorElement.textContent =
        } else {
          // Send the token to your server
          console.log(result.token);
          return result.token; 
        }
    });
}, 

the console.log outputs undefined to the console. I am calling that function when the form is submitted. And assigning the result to a another object prop

stripeOb.token = stripeOb.getStripeToken(stripeOb.stripeCard);

I then use the object prop in another function:

stripeOb.stripeTokenHandler(stripeOb.token);

Which calls:

`stripeTokenHandler : function(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token);
    form.appendChild(hiddenInput);

    console.log(token);
    // Submit the form
    //form.submit();
}`

The console log in the stripeTokenHandler returns undefined first, then the console.log from the getStripeToken outputs the Token Object.

Why is the first function console.log outputting correct after the second function console.log and why is the stipeOb.token not getting set to the the result?

TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88
  • 1
    That's an asynchronous function, you cant return a value from an asynchronous function like that because the return happens before the data has been calculated. See http://stackoverflow.com/questions/7104474/how-does-asynchronous-javascript-execution-happen-and-when-not-to-use-return-st – Wesley Smith Apr 26 '17 at 23:08

0 Answers0