问题描述
尝试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。