如何在node.js

时间:2015-11-08 20:13:18

标签: javascript ajax node.js promise

我正在使用Stripe构建结帐流程并运行一系列功能来处理付款事件。在许多情况下,必要的客户信息将存储在我的末尾(如customerToken),并且我能够将该信息传递给向客户收费的代码并且一切正常。

但是,我并不完全确定如何处理用户尚未拥有customerToken的事件,并且必须创建一个必须创建而不重复一堆代码,因为在我得到某些内容之前会触发从Stripe API返回。

我尝试在创建customerToken的函数上设置一个承诺但是 - 假设我并没有完全误解承诺 - 如果该信息已经存在并且代码永远不会执行,则承诺将无法实现。

我也看到有一些节点模块强制等待调用(比如https://github.com/yortus/asyncawait),但我是Node的新手,并想知道是否有更真实的节点方式处理事情。

我现在所拥有的内容可以简化为:

// If the user doesn't already have Stripe issued customer information 
if (customerToken === null){

    function() {

        // Asynchronous call to Stripe to get the data that will be stored as customerToken
        Stripe.customers.create({
            source: stripeToken,
            email: customerEmail,
        }).then(function(customer){
            // store customerToken on my end
            request({
                url:'[anAPI]',
                method: 'POST',
                json: {customerToken: customer}
            });
        });
    }
}

function() {
    // Charge the client based on customerId
    Stripe.charges.create({
        amount: price
        currency: 'usd',
        customer: customerToken.id,
        description: description
    });
}

// a bunch of other code that similarly needs a customerToken to function

我不知道我是否要求一些不能存在的东西,或者我是否错过了一个基本概念而且我找不到一个明确的答案到现在为止。对不起,如果这很明显!

1 个答案:

答案 0 :(得分:0)

您可以使用始终返回public class MainActivity extends AppCompatActivity { EditText mess; TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mess = (EditText) findViewById(R.id.editText); txt = (TextView) findViewById(R.id.textView); } public void onClick(View v) { if (txt.getText().toString().equals("")) { String editTextValue = mess.getText().toString(); txt.setText(editTextValue); } else { txt.setText(""); mess.setText(""); } } } 履行承诺的结构,如下所示:

customerToken

这个想法是这个函数总是返回一个promise,当它被解析时,它的解析值将是客户令牌。在某些情况下,承诺会立即得到解决,而在其他情况下则需要更长时间才能解决。

因此,如果令牌已经可用,您只需将该令牌作为promise值返回已解决的promise。如果令牌不可用,则返回一个承诺,该令牌将在令牌可用时解析。然后,调用者可以使用promise而无需知道采用了哪条路径。