I have this function
async function getLineItems(session_id) {
var lineItems = []
await stripe.checkout.sessions.listLineItems(
`${session_id}`,
function(err, data) { // this function is called asynchronously, but I need it synchronous
lineItems = data.data
}
)
return lineItems // this is called before i get the data
}
And I need to somehow make the function in stripe.checkout.sessions.listLineItems
synchronous.
Or somehow return lineItems
after the function is called. Right now the function returns an empty array every time.
CodePudding user response:
When using the await
keyword you could assign the return value of the fulfilled promised to variable like so :
async function getLineItems(session_id) {
try{
const lineItems = await stripe.checkout.sessions.listLineItems(`${session_id}`)
return lineItems.data;
} catch(e){
//handle error
}
}
Since listLineItems
is a paginated API I would strongly recommend using auto-pagination to collect all the lineItems like so
async function getLineItems(session_id) {
try{
const lineItems = [];
for await (const lineItem of stripe.checkout.sessions.listLineItems(`${session_id}`)) {
lineItems.push(lineItem);
}
return lineItems;
} catch(e){
//handle error
}
}