What are the reasons behind loading failures and the subsequent failure to resolve promises?

Here is a snippet of code that is part of a larger directive:


        var imageArray = [];
        for (var i = 0; i < $scope.abbreviations.length; i++) {
          imageArray[i] = new Image();
          imageArray[i].src = $scope.abbreviations[i].imgPath;
         };
        console.log(imageArray);

        function preLoad() {

            var promises = [];

            function loadImage(src) {
                return $q(function (resolve, reject) {
                    var image = new Image();
                    image.src = src;
                    image.onload = function () {
                        resolve(image);
                        console.log('onload:', src);
                    };
                    image.onerror = function (e) {
                        reject(e);
                        console.log('onerror:', e);
                    };
                })
            }
            imageArray.forEach(function (src) {
                console.log('forEach:', src);
                promises.push(loadImage(src));
            });

            return $q.all(promises).then(function (results) {
                console.log('Promises resolved with', results);
                $scope.results = results;
            });
        }
        preLoad().then(function () {
            console.log('Ready for next activity...');

This screenshot displays the logs from my console:

https://i.sstatic.net/uQJxL.png

Question: Why is the loading function failing and why aren't the promises being resolved as expected?

Answer №1

The issue lies within this block of code:

imageArray.forEach(function(src) {
   ...
}

When using forEach, a callback is passed an element of imageArray, which is already an Image object. This results in loading failures when assigned to a new Image's source.

To resolve this, consider avoiding the loop at the start of your code and enhancing the forEach callback to function with the original object. Alternatively, utilizing .map provides a cleaner approach:

promises = $scope.abbreviations.map(function(imgObj) {
   return loadImage(imgObj.imgPath);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

Transforming an unconventional date format into a proper date representation

I have a spreadsheet with over 100,000 dates stored in the following format: Thursday 29th of October 2015 01:06:21 PM Converting these dates into a usable format is proving to be a challenge. Whether it's YYYY/MM/DD or any other standard format, I ...

Encountering a dilemma during the docker build process with npm install is frustrating, especially when faced with an error message like: "Invalid response body when attempting

Encountering a docker build issue with npm install that seems to only occur inside the docker environment. The process works perfectly on my operating system Error Step 6/8 : RUN npm cache clear --force && npm install --legacy-peer-deps ---> ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code: HTML <div ng-app='maptesting'> <div ng-controller="MapCtrl"> <div id="map_canvas" ui-map="myMap" style ...

Is there a more effective approach to designing a login screen?

I am just starting out with angular js and this login page is my first step. I have created a basic login form, but when I click on the login() button, the form() does not get submitted and it keeps showing an error message saying "invalid username and pas ...

We encountered a surprise issue: "/Users/username/package.json: Unexpected character \ in JSON at index 1" – this is not a duplicate question

While running the yarn command in various projects, I encountered the same error consistently. Error message: "An unexpected error occurred: "/Users/name/package.json: Unexpected token \ in JSON at position 1". Trace: SyntaxError: /Users/name/pack ...

Exploring the ancestors of an element

JS <script> $('.btn').click(function(e){ target = e.target; parent = target.parentNode.parentNode; console.log(parent); }); </script> HTML <div class="card" sty ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

Sorting Tables (Implementing ng-repeat and eliminating duplicate column names with ng-if)

I have a table with data displayed using ng-repeat and it is currently sorted properly. To view the initial setup, check out the first fiddle. http://jsfiddle.net/HB7LU/10201/ <tr ng-repeat="each in list | orderBy:predicate:reverse"> I am aiming t ...

Is it possible to capture key events within a frame even when the source differs?

I'm having trouble setting up a keydown listener on my page. The issue is that there's an iFrame within the page, and whenever I click inside it and press a key, the handler doesn't work. I've tried different methods from online resourc ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Checking the format of a postal code or zipcode using a regular expression

My goal is to validate zip codes or pin codes in address fields. As a result, I am working on writing a regular expression that only allows characters a-z (upper and lower case), digits 0-9, round brackets (e.g. ()), hyphens -, and spaces. However, there a ...

Differences between angular.isDefined() and obj.hasOwnProperty()

When working with angular.js, how should I handle objects that may or may not have a status? What are the pros and cons of using angular.isDefined() versus item.hasOwnProperty() in this scenario? var checkStatus = function(item){ if(angular.isDefine ...