Firebase getSignedUrl inside loop



我需要获取'bucket/loads/:loadID'路径中所有文件的网址。我能够在名为"文件"的数组中获取这些文件。然后我过滤它(我得到 endFiles 数组(。现在我只需要一个名为url的新数组来推送所有url(getSignedUrl(。但我不知道该怎么做。我需要在循环(endFiles.forEach(中获取签名的网址,并将其推送到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 => {
//....
});
})

最新更新