我在 angular2 项目中遇到了 for 循环和 Promise 的问题。 我需要触发几个返回 promise 的方法。在 promise 之后,我想使用 Promise.all(variable).then(funtion(result){.......}; 填充类中的数组。 当我想在 Promise.all 中访问数组时,控制台提示错误
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];
}
});
...
为什么我此时无法访问 this.item?有人可以告诉我如何解决我的问题
最佳答案
this.item
访问 function (result){...}
的上下文,我想您需要外部上下文。
改用箭头函数,因此:
Promise.all(promises)
.then((result) => {
...
});
关于javascript - Waitfor Promises 在 for 循环中完成(Typescript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44208658/