已创建等待承诺 Array.map return <pending>
Awaited Promises created Array.map return <pending>
我正在使用 google-cloud-functions 在将文件上传到 Google 云存储时触发缩略图创建。
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
// Removed code not relevant to the problem
// Download file from bucket.
await file.download({destination: tempLocalFile});
const uploadPromises = sizes.map(async size => {
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
// Generate a thumbnail using Sharp.
await sharp(tempLocalFile).resize(width, height).toFile(tempLocalThumbFile);
console.log('Thumbnail created at', tempLocalThumbFile);
return thumbFile.getSignedUrl(config);
});
// Get the Signed URLs for the original image.
const results = await Promise.all([
uploadPromises,
file.getSignedUrl(config),
]);
console.log(results[0]);
});
我希望最后 console.log 输出的是一个大小为 4 的数组,其中每个元素都包含 getSignedurl() 函数的回调。相反,我现在每次得到的是一个大小为 4 的数组,其中所有元素都是承诺的。
因为我已经在等待 Promise.all() 我做错了什么导致这个问题结束?
尝试 spreading uploadPromises
在 Promise.all
:
const results = await Promise.all([
...uploadPromises,
file.getSignedUrl(config),
]);
问题是 uploadPromises
已经是一个数组,而您将其作为另一个数组的元素传递。通过使用 spread syntax,您可以将 uploadPromises
数组扩展为其元素。
我正在使用 google-cloud-functions 在将文件上传到 Google 云存储时触发缩略图创建。
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
// Removed code not relevant to the problem
// Download file from bucket.
await file.download({destination: tempLocalFile});
const uploadPromises = sizes.map(async size => {
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
// Generate a thumbnail using Sharp.
await sharp(tempLocalFile).resize(width, height).toFile(tempLocalThumbFile);
console.log('Thumbnail created at', tempLocalThumbFile);
return thumbFile.getSignedUrl(config);
});
// Get the Signed URLs for the original image.
const results = await Promise.all([
uploadPromises,
file.getSignedUrl(config),
]);
console.log(results[0]);
});
我希望最后 console.log 输出的是一个大小为 4 的数组,其中每个元素都包含 getSignedurl() 函数的回调。相反,我现在每次得到的是一个大小为 4 的数组,其中所有元素都是承诺的。
因为我已经在等待 Promise.all() 我做错了什么导致这个问题结束?
尝试 spreading uploadPromises
在 Promise.all
:
const results = await Promise.all([
...uploadPromises,
file.getSignedUrl(config),
]);
问题是 uploadPromises
已经是一个数组,而您将其作为另一个数组的元素传递。通过使用 spread syntax,您可以将 uploadPromises
数组扩展为其元素。