1

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?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Tom Walsh
  • 119
  • 2
  • 12
  • 1
    Scope isn't the issue at all. `await files.forEach()` just isn't doing what you expect. foreach loops require special treatment. – Doug Stevenson Sep 19 '19 at 15:30
  • Ok, thanks. how would you suggest working around this, and what special treatment does .forEach() require exactly? my brain is fried trying to figure this out :/ – Tom Walsh Sep 19 '19 at 15:56
  • Did you read the answers in the marked duplicate? – Doug Stevenson Sep 19 '19 at 17:00
  • sorry its the first time ive seen a marked duplicate, I noticed it right after I commented. Thanks for the help it worked perfectly. As a matter of interest had you known about this issue from previously and so knew there was an answer or did you search to first find an answer. I often get stuck trying to correctly articulate my issue so I can search for relevant solutions and I am wondering is this just a matter of experience? – Tom Walsh Sep 20 '19 at 00:02
  • 1
    This is a very common question (as you can see from all the upvotes on the duplicate). I knew to search for it because it's so common. – Doug Stevenson Sep 20 '19 at 05:40

0 Answers0