简体   繁体   中英

Making API calls await

I have this code:

function createPlan(amount) {
    return stripe.plans.create({
        product: 'DigitLead website evaluation tool',
        nickname: 'DigitLead website evaluation tool monthly charge',
        currency: 'cad',
        interval: 'month',
        amount: amount,
    });
}

var product = stripe.products.create({
    name: 'DigitLead website evaluation tool monthly charge',
    type: 'service',
});

console.log(time);
if (time === '1') {
    var amount = 1499;
    var days = 30;
    var plan = createPlan(1499);
}
else if (time === '3') {
    amount = 999 * 3;
    days = 90;
    plan = createPlan(999);
}

plan.then(p => console.log("p " + p));
if (typeof req.user.stripeId === undefined) {
    var customer = stripe.customers.create({
        email: req.user.username,
        source: req.body.stripeToken,
    });
}

It looks good, but the problem is, this code is asynchronous. So when I try to create a plan using the product variable, it doesn't exist.

I could use the then chaining, but it would be messy as all hell. I was trying to get it done with adding await like this:

var product = stripe.products.create({
    name: 'DigitLead website evaluation tool monthly charge',
    type: 'service',
});

, but node just said:

/home/iron/Documents/Projects/digitLead/routes/payment.js:46
var product = await stripe.products.create({
    ^^^^^

    SyntaxError: await is only valid in async function

I don't want to use callback hell, so I don't really know what to do. In normal code I'd just write the function saying async and return a promise. Here, I'm using Stripe API, so I cannot really edit anything.

We can only use await in async function. Therefore you may wrap it in a async IIFE:

var product = (async(name, type) => await stripe.products.create({
  name,
  type
}))(name, type);

await can only be used within an async function. So you will need to mark the function you are inside as async . If you are not inside a function, you will need to wrap your code into a function.

You will then be able to use either await on the code line, or use the Promise .then syntax. For example:

async function createProduct(name, type) {
    return await stripe.products.create({name, type});
}

Your syntax error just means you need to mark the function as async. If stripe.plans.create is async, you can add awaitable to it.

async function createPlan(amount) {
    return await stripe.plans.create({
        product: 'DigitLead website evaluation tool',
        nickname: 'DigitLead website evaluation tool monthly charge',
        currency: 'cad',
        interval: 'month',
        amount: amount,
    });
}

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