我尝试使用promises链接2个Firebase查询,因为我需要第一个查询的结果来获取第二个。以下是2个查询的结构:
QUERY FOR VALUE A:
private getValueA(){
var queryEvent = (result):void =>{
console.dump(result);
this._valueA = result.value;
}
return firebase.query(
queryEvent,
FirebaseValueAPath,
{
singleEvent : true,
orderBy : {
type: firebase.QueryOrderByType.CHILD,
value: 'since'
}
});
}
QUERY FOR VALUE B:
private getValueB{
let FirebaseValueBPath :string = this._valueA
var queryEvent = (result) :void =>{
console.dump(result);
if(result.value){
this._valueB = result.value;
}
}
return firebase.query(
queryEvent,
FirebaseValueBPath,
{
singleEvent : true,
orderBy : {
type : firebase.QueryOrderByType.CHILD,
value : 'since'
}
});
}
}
然后我尝试通过执行以下操作将它们链接在一起:
constructor(){
this.getValueA().then(
(success) :void => {
this.getValueB();
});
}
结果如下:
console.log(result)
函数在 console.log(result)里面打印
getValueA 功能(为什么??)this.valueA
在undefined
中getValueB
,使我的查询无效我的代码出了什么问题?我应该使用另一种方法来解决这个问题吗? 提前感谢您查看:)
答案 0 :(得分:1)
使用promises时,您必须在回调中解析结果。 请找到以下代码:
class GetData {
constructor() {
this.getValueA()
.then(resultA => this.getValueB(resultA));
}
getValueA() {
return new Promise<string>((resolve, reject) => {
firebase.query(
(result) => {
resolve(result.value); // Resolve => returns the result
},
FirebaseValueAPath,
{
singleEvent : true,
orderBy : {
type: firebase.QueryOrderByType.CHILD,
value: 'since'
}
}));
});
}
getValueB(valueA: string) {
return new Promise<string>((resolve, reject) => {
firebase.query(
(result) => {
resolve(result.value); // Resolve => returns the result
},
valueA,
{
singleEvent : true,
orderBy : {
type: firebase.QueryOrderByType.CHILD,
value: 'since'
}
}));
});
}
}