【发布时间】:2018-01-11 22:46:57
【问题描述】:
尝试使用 Provider 从使用 4 级嵌套回调函数的 firebase 服务器获取数据。这是我的提供者的样子。
import { Injectable } from '@angular/core';
declare var window;
@Injectable()
export class SettingsProvider {
constructor() {
}
public async getFireBaseRemoteConfig(): Promise<any> {
if (window["FirebasePlugin"]) {
await window["FirebasePlugin"].fetch(600, async result => {
// activate the fetched remote config
console.log(JSON.stringify(result)); //Always "OK"
await window["FirebasePlugin"].activateFetched( async (bool) => {
await this.getSliderImageURLs().then((d) => {
console.log("d", d);
return d;
});
});
})
}
}
public async getSliderImageURLs(): Promise<any> {
var urls = [];
await window["FirebasePlugin"].getValue("slider_images", result => {
urls = JSON.parse(result);
console.log("FROM getSliderImageURLs()");
console.log(urls)
return Promise.resolve(urls);
})
}
}
我希望执行顺序是 getFireBaseRemoteConfig 函数仅在 getSliderImageURLs 函数获取数据并返回时才返回。
根据文档,功能应按以下顺序执行:
fetch -> activateFetched -> getValue
在我的页面中,我是这样使用它的。
console.log(this.settingsProvider.getFireBaseRemoteConfig()); // Just for testing
我做错了什么?非常感谢任何帮助。
编辑:添加控制台日志
OK
d undefined
FROM getSliderImageURLs()
["","","",""] //this is my URLs array
【问题讨论】:
-
您的代码有几个问题。请查看异步等待使用情况。一方面,您没有在
getSliderImageUrl中返回任何内容,getValue是否返回承诺? -
感谢您的评论。不,getValue 不返回承诺。我需要返回 getValue 返回的值(来自函数)。
-
可以添加控制台日志吗?
-
@Ben 刚刚添加了控制台日志。顶部的函数不等待底部的函数。它在底部函数返回我需要的实际数据之前完成执行。
标签: typescript asynchronous dependency-injection async-await ionic3