Reputation: 5049
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.
Upvotes: 0
Views: 723
Reputation: 506
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);
Upvotes: 3
Reputation: 4164
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});
}
Upvotes: 2
Reputation: 8597
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,
});
}
Upvotes: 2