I am a Promise/JS/ES6 n00b. Having trouble with this.
let downloadImage = (imageLink) => new Promise((res, rej) => {
let imageName = imageLink.split("/").reverse()[0];
https.request(imageLink, (response) => {
let data = new Stream();
response.on('data', (chunk) => {
data.push(chunk);
});
response.on('end', () => {
fs.writeFileSync('app_data/'+imageName, data.read());
return res(imageName);
});
}).end();
});
I then try to utilize the above code by using the below:
let imagesArray = ["https://example.com/image1.jpg", "https://example.com/image2.png"];
let downloadedImagesArray = [];
for(let i = 0; i < imagesArray.length; i++){
downloadImage(imagesArray[i]).then(
(imageName) => {
//START NEW OBJECT
let picObj = {
id: new Date().toISOString(),
imageName: imageName
};
//ADD OBJECT TO ARRAY
downloadedImagesArray.push(picObj);
}
);
}
console.log(downloadedImagesArray); //THIS STILL RETURNS AS A BLANK ARRAY
I am able to download the images, but I am unable to see the picObj
being added to the array downloadedImagesArray
. Is this a variable scope issue? Is downloadedImagesArray
inside the promise using a different chunk of memory? I was trying to apply solutions I have found on here to my situation to no avail. I know I am going about this in a dumb way. Any help here and an explanation to clear it up for me would be tremendous. Thanks in advance.