猿问

如何访问forEach中的外部变量?

这是代码片段。我想访问每个内部的 imagePath 数组。


...


const imagePath=[];

             

req.files.images.forEach(async (image) => {

   let extName = path.extname(image.name);

   var dest = path.join(__dirname, '..', 'public', 'images', 'items');

   var imgPath = await saveFile(image, dest, itemName, extName);

   imagePath.push(imgPath); // this line

})

...


函数式编程
浏览 157回答 1
1回答

慕村225694

通常,imagePath可以在循环中轻松访问forEach。但是,您的forEach回调是异步的。如果在循环console.log(imagePath)之后立即执行 a forEach,您将得到一个空数组。一个简单的解决方法是使用for…in循环。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答