【发布时间】: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