如何从Promise响应中获取价值并将其分配给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);
}

任何人都可以帮助我纠正上述功能,以便我可以重用Promise值。

解决方法

您正在使用对getPendingOrdersCount的异步调用,因此在执行.then之前将执行console.log("response",response);,这就是为什么它不会在.then之外提供数据。

您可以从dislayResult调用.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);
}
,

假设getPendingOrdersCount返回Promise,则可以简单地使用async/await的概念。例如:

const response = await this.restapi.getPendingOrdersCount(this.items[i].store._id,this.user._id);
console.log(response); // now it has some values 

请注意,您只能在await函数内使用async。因此,如果要在getPendingOrdersCount之类的函数中调用ngOnInit(){},则应将其更改为async ngOnInit(){}

您可以详细了解async/await here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...