Asynchronous Errors

You are here

1 post / 0 new
SDKSupport
Asynchronous Errors

We recently had an integrator approach us with issues calling .doPayment() where the data and authKey were not populating. We determined they were attempting to send the request before they got the authKey back. Our development team was able to provide some explanation as to how this may happen when using PaymentsJS or JavaScript in general. 

Short Version:   You’re trying to send the request before you get the authKey back. You need to move $REQUEST.doPayment into the callback function of the ajax request.

Long Version:    JavaScript is single-threaded so you can only do one thing at a time. The classical solution to this problem is the callback function. When you know an operation is going to take some non-trivial amount of time to complete, you run is asynchronously, and give it a callback function. Since you’re using jQuery’s “$.get” function to get your authKey, which asynchronously makes a GET request. The function signature looks like this (roughly):

 
$.get(
     'https://www.example.com', // <--URL
     { someData: 'whatever' } // <-- data to send
     () => { } // <-- CALLBACK FUNCTION!
)
 

So let’s say we do this:

 
$.get(
     { someData: 'whatever' },
     () => {
     console.log('a')
     }
)
 
console.log('b')
 

This logs “b” then “a”, because JavaScript doesn’t execute the callback function until the GET request completes.

This is where the issue comes in, which is something like this:

 
$.get(
     { someData: 'whatever' },
     (data) => {
          $CORE.Initialize(data)
     }
)
 
$REQUEST.doPayment();
 

This tells JavaScript to “get an authKey, and run a payment while you’re waiting”. This is incorrect as we need to wait for the authKey before running the payment. This is why you simply need to move the logic into the callback:

 

$.get(
     { someData: 'whatever' },
     (data) => {
          $CORE.Initialize(data)
          $REQUEST.doPayment();
     }
)
 

I hope this helps clarify things. Please let us know if you need any additional information or assistance. You are welcome to post here in the forums or to contact us directly at [email protected]