如何在循环错误中修复意外的“await”

Man*_*tas 2 javascript google-cloud-functions

Eslint 给了我一个错误“await在循环中意外”。我明白这个问题,但找不到修复代码的方法。

我已经阅读了 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*lms 7

   const results = await Promise.all(imagePaths.map(async imagePath => {
     // this now runs concurrently ...
     return uploadedFile[0].metadata.mediaLink;
   }));
Run Code Online (Sandbox Code Playgroud)

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