I have this function with the following code below:
app.post('/create-checkout-session', async (req, res) => { console.log(req.session.username) let price = "" var getUserPaymentData = "select * from INVOICES where USER = '" + req.session.username + "'" ibmdb.open(ibmdbconnMaster, function(err, conn) { if (err) return console.log(err); conn.query(getUserPaymentData, function(err, rows) { if (err) { console.log(err); } for (var i = 0; i < rows.length; i++) { console.log("rows of lengths are: " + rows.length) var price1 = rows[i]["AMOUNTOWED"] console.log(rows[i]["USER"]) price = parseInt(price1) console.log(price1) } conn.close(function() { console.log("closed the function /create-checkout-session"); }); }); }) console.log(price) const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [ { price_data: { currency: 'usd', product_data: { name: 'Marcos Swim School Payment', }, unit_amount: price, }, quantity: 1, }, ], mode: 'payment', success_url: `https://xxx.ca/`, cancel_url: `https://xxx.ca/cancel`, }); res.json({ id: session.id }); });
I’m basically checking how much the user owes to me, and then redirecting to checkout. However, it is totally skipping over the query and not logging anything, and then throwing the error that no price is defined. This is because I am trying to set the price after I query my table. How do I fix this?
Advertisement
Answer
ibmdb.open
is a function that uses a callback, and so it returns immediately. You either need to await
its result if it supports async/await, or move all of the code below it – the const session = await stripe.checkout.sessions.create()
and res.json()
calls – inside the callback.