简体   繁体   中英

Waitfor Promises to finish in a for-loop (Typescript)

I have a issue with a for-loop and promises in my angular2 project. I need to fire several method which return a promises. After the promises I want to fill a array in the class by using the Promise.all(variable).then(funtion(result){.......}; When i want to access the array with in the Promise.all the console promte the 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, I can't acces this.item at that point? Does anybody could give me a idee how I would solve myproblem

this.item accesses the context of the function (result){...} and I suppose you want the outer context.

Use arrow functions instead, therefore:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM