【问题标题】:Awaited Promises created Array.map return <pending>Awaited Promises created Array.map return <pending>
【发布时间】:2020-03-15 23:47:13
【问题描述】:

我正在使用 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() 我做错了什么导致这个问题结束?

【问题讨论】:

    标签: javascript node.js asynchronous google-cloud-functions es6-promise


    【解决方案1】:

    在Promise.all 中尝试spreading uploadPromises:

    const results = await Promise.all([
       ...uploadPromises,
       file.getSignedUrl(config),
    ]);
    

    问题是uploadPromises 已经是一个数组,而您将它作为另一个数组的元素传递。通过使用spread syntax,您可以将uploadPromises 数组扩展为其元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 2016-12-06
      • 1970-01-01
      • 2021-01-08
      • 2018-05-24
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多