I'm trying to take the metadata from some firebase storage objects, and transform the metadata into a simple list of objects. The end goal is to sort the objects in the list by the time they were uploaded.
However, I am having trouble with the use of async functions and the scope of them I think.
The code is executed as a firebase function, and this is the code:
exports.listItems = functions.storage.object().onFinalize(async (object) => {
const [files] = await storage.bucket(bucketName).getFiles();
async function metadata(files) {
let items = [];
await files.forEach(async (file) => {
const [metadata] = await storage
.bucket(bucketName)
.file(file.name)
.getMetadata();
let item_object = { name: metadata.name, updated: metadata.updated };
console.log(item_object);
items.push({ yup: 'yuppa' });
items.push(item_object);
});
return items
}
let items = await metadata(files)
items.push('test')
console.log(items)
});
The above code logs the following to the console:
[ 'test' ]
Function execution took 501 ms, finished with status: 'ok'
{ name: 'public_wall/_2420565.jpg', updated: '2019-09-19T14:52:22.254Z' }
{ name: 'public_wall/_2420498.jpg', updated: '2019-09-19T14:39:22.278Z' }
So the code within the metadata function is only executing after the rest of the function has ended, and as such is not being appended to the list. How can I get around this?