Closed hansy closed 4 years ago
Since I was using this in an async serverless function I needed to wait for the Mixpanel request to complete. I ended up turning track
into a Promise via promisify
to await the Mixpanel response.
@hansy Thanks for this tip. Saved me a ton of time. I really miss having promises in this API.
It's kinda ridiculous. The library just doesn't work in AWS lambda at all unless you wrap it since the callback doesn't have time to fire before the lambda ends.
If anyone wants an example of how to create a promise wrapper here is one.
/**
* Due to the fact that the mixpanel library does not support promises
* we have to wrap the track function in a promise. Otherwise the
* lambda function will finish before the request has been sent.
* @param event - The event to track
* @param properties - The properties to track with the event
* @param mixpanel - The mixpanel instance
* @param userId - The user id
* @returns A promise that resolves when the track request has been sent
*/
async function mixpanelAsyncTrack({
event,
properties,
mixpanel,
userId,
}: {
event: string
userId: string
properties?: { [key: string]: string | number | boolean | undefined }
mixpanel: Mixpanel.Mixpanel
}) {
return new Promise((resolve, reject) => {
mixpanel.track(event, { distinct_id: userId, properties }, (err) => {
if (err) {
reject(err)
} else {
resolve('success')
}
})
})
}
@walterholohan Thanks! Have been struggling for hours to set up Mixpanel event tracking in a NextJS API route (which gets turned into a serverless lambda function when deploying to Vercel into production). This works great!
I'm not sure why, but no events are being sent via the
track
function.I don't even know how to debug this. I even tried adding a callback argument to look for an error, but nothing:
What am I doing wrong?
System info: Mixpanel v0.13.0 Node v14.5.0 MacOS Catalina 10.15.6