条带化createToken同步

时间:2019-04-19 16:02:13

标签: javascript stripe-payments

当前,我有以下验证码:

var validatePayment = function() {
        stripe.createToken(card).then(function(result) {
            if (result.error) {
              // Inform the customer that there was an error.
              var errorElement = document.getElementById('card-errors');
              errorElement.textContent = result.error.message;
              return false;

            } else {
              stripe_token = result.token;
              return true;

            }
          });

        return false
    }

并将验证付款称为:

if(validatePayment() {
//Do Something
} else {
//Don't do something
}

调用validatePayment总是错误的,因为它具有异步功能。 stripe.createToken(card)是否有办法。有没有办法使其同步?

2 个答案:

答案 0 :(得分:1)

由于stripe.createToken(card)创建了一个诺言,您可以返回该诺言,然后在没有条件(如当前,这是同步的)的情况下使用.then() / .catch()确定结果。

var validatePayment() {
    return stripe.createToken(card).then(function(result) { //<-- note return
};

validatePayment()
    .then(() => { /* payment was OK */ })
    .catch() => { /* uh-oh... */ });

答案 1 :(得分:0)

您可以尝试使用诺言

    var validatePayment = function() {
                    return new Promise((resolve,reject)=>{ 
                      stripe.createToken(card).then(function(result) {
                        if (result.error) {
                          // Inform the customer that there was an error.
                      var errorElement = document.getElementById('card-errors');
                      errorElement.textContent = result.error.message;
                      return false;

                } else {
                  stripe_token = result.token;
                  return true;

                }
              });
    }).then(stats => {
            resolve(stats)
        }).catch( e =>
          reject()
)