简体   繁体   English

如何在Node.js中使用Promise或同步调用处理if语句

[英]How to deal with an if statement using promises or synchronous calls in node.js

I'm building a checkout flow using Stripe and running a series of functions for handling a payment event. 我正在使用Stripe构建结帐流程,并运行一系列处理付款事件的功能。 In many cases the necessary customer information will be stored on my end (as customerToken ) and I'm able to just pass that information to the code that charges the customer and everything works well. 在许多情况下,必要的客户信息将存储在我的终端上(作为customerToken ),并且我能够将这些信息传递给向客户收费的代码,并且一切正常。

However, I'm not exactly sure how to deal with the event in which the user does not already have customerToken and one must be creating without repeating a bunch of code as stuff fires before I get something returned from the Stripe API. 但是,我不确定如何处理用户尚未拥有customerToken的事件,并且在我从Stripe API返回某些内容之前,必须在不重复执行一堆代码的情况下创建事件。

I tried setting up a promise on the function that creates the customerToken but - assuming I'm not totally misunderstanding promises - that promise wouldn't be fulfilled if that information already existed and the code would never execute. 我尝试在创建customerToken的函数上设置一个Promise,但是-假设我不是完全误解了Promise-如果该信息已经存在并且代码将永远无法执行,则该Promise将无法实现。

I've also seen there are node modules that force calls to wait (like this https://github.com/yortus/asyncawait ) but I'm new to Node and wondering if there is a more true-to-node way of handling things. 我还看到有一些节点模块可以强制调用等待(例如https://github.com/yortus/asyncawait ),但是我是Node的新手,想知道是否还有一种更真实的方法处理事情。

What I have now can be simplified to look like this: 我现在所拥有的可以简化为:

// 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

I have no idea if I'm asking for something that just can't exist or if I'm missing a basic concept and I haven't been able to find a clear answer searching up until now. 我不知道我是否要问一些根本不存在的东西,或者我是否缺少一个基本概念,并且直到现在我都找不到一个明确的答案。 Sorry if this is obvious! 抱歉,这很明显!

You can use a structure that always returns a promise fulfilled with the customerToken like this: 您可以使用始终返回由customerToken履行的承诺的结构,如下所示:

function getToken() {
    if (customerToken) {
        return Promise.resolve(customerToken);
    } else {
        // Asynchronous call to Stripe to get the data that will be stored as customerToken
        return Stripe.customers.create({
            source: stripeToken,
            email: customerEmail,
        }).then(function(customer){
            // Note: this request() is sent asynchronously and
            // this promise does not wait for it's response
            // You could make it wait by returning a promise here
            // store customerToken on my end
            request({
                url:'[anAPI]',
                method: 'POST',
                json: {customerToken: customer}
            });
            return customer;
        });    
    }
}

getToken().then(function(token) {
    // use the token here
});

The idea is that this function always returns a promise that, when resolved, will have its resolved value be the customer token. 想法是此函数始终返回一个承诺,该承诺在解决时将以其解决的价值作为客户令牌。 In some cases, the promise is immediately resolved, in others it takes longer to resolve. 在某些情况下,承诺会立即得到解决,而在另一些情况下,则需要更长的时间来解决。

So, if the token is already available, you just return a resolved promise with that token as the promise value. 因此,如果令牌已经可用,则只需返回已解析的承诺,并将该令牌作为承诺值即可。 If the token is not available, you return a promise that will be resolved with the token when it is available. 如果令牌不可用,您将返回一个承诺,该承诺将在令牌可用时由令牌解决。 Then, the caller can just use the promise without having to know which path was taken. 然后,调用方可以使用承诺而不用知道采用哪个路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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