Awaiting the completion of Promises within a for-loop (Typescript)

I'm struggling with a for-loop and promises in my angular2 project. I have multiple methods that return promises, and after these promises are resolved, I want to populate an array in the class using Promise.all(variable).then(function(result){.......}; However, when I try to access the array within the Promise.all, the console throws an error

core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'item' of undefined

...

public item;
allItems = [];


public method() {
  var promises =  [];          
  this.dbService.getItem('myKey', 'table')
  .then((data) => {        
    this.myArrayNumber = data;
    for (let i = 0; i < this.myArrayNumber.length; i++) {                                      
      promises.push(this.dbService.getItem(this.epodLiefernr[i], 'lieferungen'));
    }

    Promise.all(promises)
    .then(function (result) {
      for (let i = 0; i < result.length; i++) {
        this.item = result[i];              
      }
    });

...

Why am I unable to access this.item at that point? Can anyone provide me with suggestions on how to solve this issue?

Answer №1

this.item retrieves the context within the function (result){...} and it seems like you are looking for the outer context.

Switch to arrow functions for that purpose:

Promise.all(promises)
.then((result) => {
...
});

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

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

Issue with JQuery dialog not triggering autocomplete

I have integrated the JQuery 1.7.2 and JQuery-UI 1.8.18 libraries with both http://docs.jquery.com/UI/Dialog and http://docs.jquery.com/UI/Autocomplete. On a standard page load, the autocomplete function works perfectly with a text box in a form. It' ...

How to transform a hyperlink into a clickable element within an absolutely positioned container

I'm currently working on a photo gallery project and using magnific popup to create it. However, I ran into an issue with the hover event on the images that displays an icon when it's hovered over, indicating that it can be clicked to view more. ...

Creating an href link within a button that is contained within a collapse component

I am grappling with an issue where my collapsed model is displaying more information about clients; however, when I click on the button inside it, instead of getting the specific client's data, I end up retrieving information for all clients. <ion ...

How to selectively filter an array of objects using another array in JavaScript

Imagine you have an array filled with objects: people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3 ...

Leverage the compiler API to perform type inference

Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

"Attempting to troubleshoot a calculator built with html, css, and js. I'm stumped as to what could

After following a tutorial on YouTube, going over the code multiple times, and still experiencing issues with the calculator. Sometimes it works fine, other times certain buttons like (+, -, x, ⁄) don't function properly. I've provided the enti ...

Utilizing ease-in effect on show more button clicks in CSS

When I click "show more," I want to have a smooth ease-in/out animation for 3 seconds. However, I am facing difficulties achieving this because I am using overflow: hidden and -webkit-line-clamp: 2; Are there any other methods to accomplish this? https: ...

Version discrepancy in module metadata

Yesterday everything was running smoothly with Angular 2 and Angular Material, but today I encountered an error when trying to run the program. Can someone please help? ERROR in Error: Metadata version mismatch for module E:/Demo/crud/ node_modules/ ...

Remove the carriage return and newline characters from a Python variable

After successfully obtaining the page source DOM of an external website, I found that it contained \r\n and significant amounts of white space. import urllib.request request = urllib.request.Request('http://example.com') response = ur ...

The offspring of a React component

How can I select a specific div in children using React without passing it as a prop? I want to transform the code snippet from: <Pane label="Tab 1"> <div>This is my tab 1 contents!</div> </Pane> to: <Pane> <div&g ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

Eliminate unnecessary spacing from the sticky container

Trying to implement a sticky menu in an angular 14 project using angular material 14 has been quite challenging for me. Initially, I attempted to use the 'fixed' position, but encountered issues where the menu would consistently return to the to ...

Dynamic form groups in Angular: Avoiding the issue of form inputs not binding to form groups

Purpose My goal is to develop a dynamic form in Angular that adjusts its fields based on an array received from the backend. For example, if the array contains ["one", "two", "three", "four"], the form should only ...

What could be causing the API link to not update properly when using Angular binding within the ngOnInit method?

Hi there, I'm currently working on binding some data using onclick events. I am able to confirm that the data binding is functioning properly as I have included interpolation in the HTML to display the updated value. However, my challenge lies in upd ...

The datepicker function is malfunctioning in a div that has been dynamically loaded through

I am experiencing an issue with loading a div populated by ajax. The datepicker does not seem to be called when the content is loaded this way. Initially, I had the datepicker loaded in the header of the main page, but even after trying to load it within ...

When utilizing RxJS, the process of filtering Observable data may not function as expected if the filtering is carried out within a separate function rather than directly within the subscribe

While attempting to filter data from an external source using the RxJS filter on Observables, I encountered an issue where all records were returned instead of just the ones meeting the filtering criteria. This problem occurred when the code was within a l ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...