我需要获取“ bucket / loads /:loadID”路径中所有文件的网址。我能够在名为“文件”的数组中获取这些文件。然后过滤(我得到endFiles数组)。现在,我只需要一个名为url的新数组即可将所有url推送到(getSignedUrl)中。但是我不知道该怎么做。我需要在循环(endFiles.forEach)中获取已签名的url,并将其推送到urls数组或类似的东西。

exports.testCloudFunc = functions.storage.object().onFinalize(async object => {
  const filePath = object.name;

  const { Logging } = require('@google-cloud/logging');
  console.log(`Logged: FILEPATH: ${filePath}`);
  const id = filePath.split('/');
  console.log(`Logged: ID: ${id[0]}/${id[1]}`);
  const bucket = object.bucket;
  console.log(`Logged: BUCKET: ${object.bucket}`);

  async function listFilesByPrefix() {
    const options = {
      prefix: id[0] + '/' + id[1]
    };
    const [files] = await storage.bucket(bucket).getFiles(options);

    const endFiles = files.filter(el => {
      return (
        el.name === id[0] + '/' + id[1] + '/' + 'invoiceReport.pdf' ||
        el.name === id[0] + '/' + id[1] + '/' + 'POD.pdf' ||
        el.name === id[0] + '/' + id[1] + '/' + 'rateConfirmation.pdf'
      );
    });

    for (let i = 0; i < endFiles.length; i++) {
      console.log(endFiles[i].name);
    }
  }
  listFilesByPrefix().catch(console.error);
});


我被困住了,需要帮助。非常感谢您的帮助。

最佳答案

getSignedUrl()方法是异步的,并返回Promise。

由于要同时执行对该方法的多次调用,因此需要使用Promise.all(),如下所示:

  async function listFilesByPrefix() {
    const options = {
      prefix: id[0] + '/' + id[1]
    };
    const [files] = await storage.bucket(bucket).getFiles(options);

    const endFiles = files.filter(el => {
      return (
        el.name === id[0] + '/' + id[1] + '/' + 'invoiceReport.pdf' ||
        el.name === id[0] + '/' + id[1] + '/' + 'POD.pdf' ||
        el.name === id[0] + '/' + id[1] + '/' + 'rateConfirmation.pdf'
      );
    });

    const config = {
       action: 'read',
       expires: '03-17-2025'
    };

    const promises = [];
    for (let i = 0; i < endFiles.length; i++) {
      console.log(endFiles[i].name);
      promises.push(endFiles[i].getSignedUrl(config));
    }

    const urlsArray = await Promise.all(promises);

    return urlsArray;
  }


  listFilesByPrefix()
  .then(results => {
     //results is an array of signed URLs
     //It's worth noting that values in the array will be in order of the Promises passed with promises.push()
     //do whatever you need, for example:
     results.forEach(url => {
         //....
     });
   })

关于javascript - Firebase getSignedUrl在循环内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60056973/

10-13 01:42