I'm trying to collect all the documents from a specific file and transform them into a Sendgrid attachment object with a content and filename property.
Step 1 and 2 are working. After step 2 I have an array of objects with some document data like the file name, type, storage URL etc.
In step 3 I want to fetch the actual file based on the storage URL and create a Sendgrid attachment object. It requires content and filename as properties.
However, with my current code, the attachments array stays empty when I'm logging the variable.
My code:
export const onStatusChanged = functions.database.ref(`files/{fileID}/general/status`).onUpdate(async (change, context) => {
const prevStatus = change.before.val();
const currentStatus = change.after.val();
if (prevStatus === currentStatus) return null;
if (currentStatus === 'email') {
// 1. Get file data
const snapshot = await change.after.ref.parent.parent.once('value');
const file = snapshot.val();
// 2. Get documents
const documents = getDocuments(file.documents);
console.log(documents);
// 3. Create attachments
const attachments = [];
documents.forEach(document => {
axios.get(document.url, { responseType: 'arraybuffer' }).then(image => {
attachments.push({ content: Buffer.from(image.data).toString('base64'), filename: document.name });
}).catch(error => {
console.log(error)
})
});
console.log(attachments) // []
// 4. Create email object
// 5. Send email
}
return null;
})
I thought by using a promise my code is synchronous?
EDIT: first I had this code
// 3. Create attachments
const attachments = documents.map(document => {
const image = await axios.get(document.url, { responseType: 'arraybuffer' });
return attachments.push({ content: Buffer.from(image.data).toString('base64'), filename: document.name });
})
console.log(attachments) // [ Promise { <pending> } ]
async.waterfalland maybe this is still done. You might be thinking about usingawait. This new keyword makes async code look synchronous, though it is still definitely async. Have you triedawaitin yourforEach?map()function. Added this code