![](/img/trans.png)
[英]Returning a value from a Javascript function that includes a Promise
[英]Returning data from provider promise function in Javascript
我有一個提供程序,應允許我從所需的API返回特定數據。 我有這樣做的功能:
public getStoryCount(key: string, val: number) {
return this.client.getEntries({
'content_type': xxxxxxxxxxxxxx,
[key]: val,
}).then((entries:any) => {
return entries.total;
});
}
這是我第一次真正使用Promise,但是我試圖在組件中調用它以獲取價值。 我希望能夠獲取console.log獲取輸出時的值entry.total。
我正在構建一個數據數組,以便在我的視圖中使用,如下所示:
this.homeScreen.push({
'count': Provider.getStoryCount('sys.id', xxxx)
});
當我console.log Provider函數時,我可以在promise中看到該值,它看起來像這樣:
__zone_symbol__state : true
__zone_symbol__value : 13 // this is the value I need to get
如何將數字13保存到數組homeScreen ['count']值中? 還是我做錯了什么?
您當前正在返回Promise
而不是實際值。 這意味着將組件代碼修改為此:
Provider.getStoryCount('sys.id', xxxx)
.then((entries:any) => {
this.homeScreen.push({
'count': entries.total
});
}
});
應該管用。
您還可以使您的Provider
服務獲取值並將其存儲為Observable,以便組件隨后可以訂閱該值。
由於Promise是異步的,因此您實際上並沒有像您想象的那樣返回entry.total。
您可能需要提供自己的回調函數,或者簡單地返回promise(由this.client.getEntries生成), then
將then附加到結果上。 它可能看起來像這樣:
public getStoryCount(key: string, val: number) {
return this.client.getEntries({
'content_type': xxxxxxxxxxxxxx,
[key]: val,
});
// The 'then' will be added later
}
// ...
// Get the promise from the provider, and invoke 'then' here.
var storyCountPromise = Provider.getStoryCount('sys.id', xxxx);
storyCountPromise.then((entries:any) => {
this.homeScreen.push({
'count': entries.total
});
});
這是一個異步操作。 你需要通過一個功能then
:
Provider.getStoryCount('sys.id', xxxx)
.then((total) => {
this.homeScreen.push({
'count': total
});
});
首先,要將承諾的結果映射到另一個值,請使用map。
public getStoryCount(key: string, val: number) {
return this.client.getEntries({
'content_type': xxxxxxxxxxxxxx,
[key]: val,
}).map((entries:any) => {
return entries.total;
});
}
然后在調用promise返回函數時使用then
獲取結果
Provider.getStoryCount('sys.id', xxxx).then((total) => ...use total...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.