0

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.

user1053263
  • 722
  • 2
  • 16
  • 33
  • 2
    No, it's not a scope issue. It's simply that the *asynchronous* `then` callbacks have not yet happened. You need to use `Promise.all` and wait for that – Bergi Nov 08 '17 at 05:59
  • @Bergi looking that up now. I figured the `console.log()` would've executed after the for loop was complete but I guess it continues to loop even when the promise is resolving. – user1053263 Nov 08 '17 at 06:03
  • 1
    Yes, the loop doesn't wait for your https requests. – Bergi Nov 08 '17 at 06:17
  • @Bergi I understand now. Thank you! Promise.all() and some map functions worked perfect, – user1053263 Nov 08 '17 at 06:50

0 Answers0