【问题标题】:How to fix Unexpected `await` inside a loop error如何在循环错误中修复意外的`await`
【发布时间】:2019-06-07 20:50:07
【问题描述】:

Eslint 给我一个错误“Unexpected await inside a loop”。 我了解问题所在,但找不到修复代码的方法。

我已阅读 eslint 文档:https://eslint.org/docs/rules/no-await-in-loop 当我将循环包装在/* eslint-disable no-await-in-loop */ 中时,它会修复错误。但是,这样做效率不高,因为每个 Promise 都会等待前一个 Promise 完成。

我的 promise 结果不相互依赖,因此它们可以同时运行。我对么? 如果有人能告诉我如何修复我当前的代码并使用 Promises,我会很高兴

const resizeImages = async imagePaths => {
    try{

        // With the line bellow everything works as expected. But without it I get error
        /* eslint-disable no-await-in-loop */

        const results = [];

        for (const imagePath of imagePaths){
            const thumbDest = path.parse(imagePath).dir + '/resized' + path.basename(imagePath);
            let tempFilePath = path.join(os.tmpdir(), path.basename(imagePath));
            console.log("Image resizing in progress: " + imagePath);

            // File is downloaded to the firebase functions environment 
            await rootBucket.file(imagePath).download({
                destination: tempFilePath
            })
            // Uploading resized image back to the folder in firebase storage 
            await spawn('convert', [tempFilePath, '-resize', '900x900', tempFilePath]);
            // Uploading resized image back to the folder in firebase storage 
            const uploadedFile = await rootBucket.upload(tempFilePath, {
                destination: thumbDest,
                metadata: metadata
            })
            console.log("Resized img successfully saved in: " + thumbDest);
            console.log("Resized img mediaLink " + uploadedFile[0].metadata.mediaLink);

            results.push(uploadedFile[0].metadata.mediaLink);                        
        }

        /* eslint-enable no-await-in-loop */

        return resizedImages = results;
    }
    catch (err){
        return console.log("Function resizeImages error: " + err);
    }
}

这是 Google Firebase 云功能的一部分,我尝试在其中创建缩略图、减小上传图片的大小并删除原始图片。

【问题讨论】:

    标签: javascript google-cloud-functions


    【解决方案1】:
       const results = await Promise.all(imagePaths.map(async imagePath => {
         // this now runs concurrently ...
         return uploadedFile[0].metadata.mediaLink;
       }));
    

    请注意,这“不是错误”。这是一个可以帮助您改进代码的警告。在这种情况下,可以并行处理不同的项目,这就是警告要告诉您的内容。不过,在循环中等待的情况是完全有道理的(例如,如果需要按顺序进行处理)。

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多