javascript - 如何从承诺响应中获取价值并将其分配给 Ionic v3 中数组中的每个对象属性
问题描述
尝试 1:我尝试使用以下函数获取数据。由于它是异步的,因此无法从此函数中获取值。
for (var i = 0; i < this.items.length; i++) {
let newitems: any = this.items;
this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
this.result = data;
console.log(this.result);
//able to get the data here
});
//Unable to get the data here.
newitems[i].pendingCount = this.result;
console.log("result", this.result);
}
尝试 2:我在上面的函数中添加了额外的变量并且确实返回了。现在我可以在这里获取这些数据,但它不是值,它是一个区域值 => t {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
let newitems: any = this.items;
for (var i = 0; i < this.items.length; i++) {
var response = this.restService.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
this.result = data;
//console.log(this.result);
return response;
});
//able to get result here but its not value, its a zone value
newitems[i].pendingCount = this.result;
console.log("response", response);
}
任何人都可以帮助我更正上述功能,以便我可以重用承诺值。
解决方案
您正在使用异步调用,getPendingOrdersCount
所以在.then
执行 之前console.log("response",response);
将被执行,这就是为什么它没有在外部提供数据.then
。
您可以调用dislayResult
函数 from.then
以获取外部数据,如下所示。
this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
this.result = data;
console.log(this.result);
//able to get the data here
displayResult();
});
displayResult() {
console.log(this.result);
}
推荐阅读
- python - 元素为 2x2 矩阵的块矩阵的逐元素张量积
- discord.py - Discord.py 如何获取不是服务器成员的用户的雪花?
- go - GO Lang Web 应用程序 - 自动编译和重新加载
- java - 从Java中的长json字符串中获取十进制数字流
- python - 在 Python 中拟合正弦余弦曲线
- django - 在子域上操作时是否需要 django-cors-headers?
- java - 如何在休眠本机查询中仅从列表中获取值我的列表返回键值对
- java - 修复 java 中交错的正则表达式替换输出
- python - 在 Django 上进行迁移
- ubuntu - /bin/sh: -c: 第 0 行:在寻找匹配的 `"' 时出现意外的 EOF