Reputation: 51
I've been working on a script using the pdf2base64 npm package to convert the PDF uploaded from a form to a Base64 string to upload to an api.
I'm taking the url from the uploaded PDF and passing it into the package I mentioned above in order to convert it to the correct format.
My code looks something like this:
const pdf2base64 = require('pdf-to-base64')
const createPayload = (name, email, pdf) {
return {
firstName: name,
email: email,
pdf: {
name: pdf.filename,
mimeType: pdf.type,
fileContent: '', // This will be replaced with a base64 string
}
}
}
exports.handler = async function( event, context ) {
const formData = JSON.parse(event.body).payload
if (formData.form_name == 'pdf-form') {
console.log("Processing PDF...")
const submission = createPayload(formData.data)
const pdfUrl = formData.data.resume.url
pdf2base64(pdfUrl)
.then( (response) => {
const result = response;
submission.pdf.fileContent = result;
console.log(submission)
return response
})
.catch( (error) => console.log(error))
}
}
However, when I run the script, my console only logs the following.
9:43:59 AM: 2021-01-26T07:43:59.806Z 608332cc-be83-4243-b986-05d6e7e5b0f0 INFO Processing PDF...
9:43:59 AM: Duration: 71.86 ms Memory Usage: 70 MB Init Duration: 132.10 ms
As you can see, any logs after "Processing PDF..." aren't showing up. What am I doing wrong?
Upvotes: 0
Views: 186
Reputation: 2973
You need to use await in the context of an async function so that you wait for the result of the pdf2base64() function call. Otherwise the main function will finish sooner than your pdf2base64 function.
exports.handler = async function( event, context ) {
const formData = JSON.parse(event.body).payload
if (formData.form_name == 'pdf-form') {
console.log("Processing PDF...")
const submission = createPayload(formData.data)
const pdfUrl = formData.data.resume.url
try {
const result = await pdf2base64(pdfUrl);
return result;
} catch(error) {
console.log(error);
}
}
}
You can read more on async/await at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
As a rule of thumb. If you mark your function as async, just use await instead of "then/catch". Makes for easier to read code too. No nesting hell if you have more complex flows. Just code which looks linear.
Upvotes: 1