[英]Waitfor Promises to finish in a for-loop (Typescript)
I have a issue with a for-loop and promises in my angular2 project. 我在angular2项目中遇到了for循环和promise问题。 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
承诺之后,我想使用Promise.all(variable).then(funtion(result){.......};来填充类中的数组。当我想在Promise中访问数组时。所有控制台提示错误
core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'item' of undefined
core.es5.js:1084错误错误:未捕获(承诺中):TypeError:无法设置未定义的属性“ item”
...
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? 为什么,那时候我不能访问this.item? 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. this.item
访问function (result){...}
的上下文function (result){...}
,我想您需要外部上下文。
Use arrow functions instead, therefore: 请改用箭头功能,因此:
Promise.all(promises)
.then((result) => {
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.