简体   繁体   中英

Javascript doesn't wait for STRIPE.COM function to finish before executing next line

stripe.com is a payment processing site like paypal.com. in two steps they actually execute a credit card. first step to validate the card information and in second pass it deduct amount and credit to merchant account. however, for me the situation is i need to verify credit card information using stripe.com. so what i did is, call a function "stripeResponseHandler" which pass CC info to stripe and get response within few seconds. it works great. But the problem is, javascript/jquery doesn't wait until that function execution finished. Fact is, i have set a variable to determine the immediate next step based on stripeResponseHandler response. is there are any way by which i can stop further execution until stripeResponseHandler function finished? Here is few lines of code:

var cc_validate=1;
function stripeResponseHandler(status, response) {  //alert('stripeResponseHandler called');
    if (response.error) {
        cc_validate=1;
    } else {  //CC info Correct. Now Charge using PHP by Submit this form
        cc_validate=0;
        alert('CC Validation passed in stripeResponseHandler call.');
    }
}
$('#btnSubmit').on('click', function(e) {
  e.stopPropagation();
    Stripe.createToken({
        number: '4242424242424242',
        cvc: '123',
        exp_month: '11',
        exp_year: '2015'
    }, stripeResponseHandler);

  alert(cc_validate); // it always output 1(but i need 0 for valid CC)
  //'execution always comes here before complete stripeResponseHandler function execution'

createToken is doing the validation asynchronously as most functions that make network calls do. Move your processing into stripeResponseHandler.

Update

It is not possible to stop and wait for a network call complete then start processing again without using callbacks. Move your furthering processing into a function and call that function from function stripeResponseHandler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM