0

I have a promise to get a bunch of images and store them in an array (it only takes square images from the source). Once the images are stored in the array, I want to console.log the array and its first index. console.log(images) works, but console.log(images[0]) outputs undefined.

        $http(req).then(function(res)

            res.data.persons.forEach(function(person, index) {
                fsImages.push($scope.getImage(person,token));
            });
            
            Promise.all(fsImages).then((results) => {
                var deleteEmptyObject = true;

                results.forEach((url) => {
                    if (!!url) {
                        let image=new Image();
                        image.onload= function(){
                            if((Math.abs(1 - (image.naturalWidth / image.naturalHeight)) < 0.1)){
                                images.push(url);
                            }
                            else {
                              console.log('not pushed');
                            }
                        };
                        image.src=url.image;
                    }
                });
                console.log(images);
                console.log(images[0]); // Result: undefined
            });
        }, function(error) {
            console.log('error');
            console.log(error);
        });
janksmap
  • 61
  • 1
  • 2
  • 7
  • 1
    `images[0]` won't be set until the first image load operation completes. It's an asynchronous operation. – Pointy Aug 05 '20 at 23:06
  • 2
    `image.onload=` is asynchronous too ... nothing to do with Promises ... this code will produce exactly the same "problem" outside of a promise – Jaromanda X Aug 05 '20 at 23:06

0 Answers0