I have a function in AWS Lambda to retrieve user details in Stripe. But the code after the function is executing first. What am I missing?
In my case, the function calls a Stripe function that returns a customer object.
I think the details of the Stripe function are not relevant for this specific question--the issue is the structure of my async/await:
module.exports.getUserName = async (event, context)=>{
[code to get customerId from stripe]
var customerName
await stripe.customers.retrieve(customerId, function(err, customer){
if (err){}
else{
customerName = customer.name
}
})
console.log('This should run after stripe.customers.retrieve')
}
Right now the console.log statement runs first. I've also tried wrapping the Stripe function in a separate async function, and also tried adding try/catch. But it's not working yet.
How can I be sure that the console log statement instead runs after stripe.customers.retrieve ?
Edit: I checked the source for the npm stripe package. All the functions do return Promises, but if you additionally supply a callback, they're scheduled to be called on the next event loop (immediately after your console.log runs).
All you need to do is simply don't provide a callback if you'll be using the promise. Use Promise.then() instead:
await stripe.customers.retrieve(customerId).then(customer => {
customerName = customer.name
resolve()
}).catch(_=>{})
Old answer (still works, but very redundant):
await is to be used with Promises, it doesn't magically convert asynchronous code to synchronous. I can see from the old-fashioned function(err, customer){ callback that your stripe.customers.retrieve() function does not return a Promise, so the await won't actually do anything.
You need to wrap it in a promise in order to use with async/await:
await new Promise((resolve,reject) => {
stripe.customers.retrieve(customerId, function(err, customer) {
if(!err) {
customerName = customer.name
resolve()
}
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With