forEach에서 외부 변수에 액세스하는 방법은 무엇입니까? [복제]
Nov 12 2020
이것은 코드 조각입니다. 각각에 대해 내부의 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
})
...
답변
Aaron_Actu Nov 13 2020 at 05:22
일반적으로 루프 imagePath
에서 쉽게 액세스 할 수 있습니다 forEach
.
그러나 forEach
콜백은 비동기 적입니다. 루프 console.log(imagePath)
직후에 수행 forEach
하면 빈 배열이 생성됩니다.
간단한 해결 방법은 for…in 루프 를 사용하는 것 입니다.