NativeScript Firebase es6承诺奇怪的行为

时间:2016-09-25 17:06:23

标签: javascript typescript firebase-realtime-database nativescript es6-promise

我尝试使用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();
   });
}

结果如下:

  1. 出于某种原因,{strong> getValueB 内console.log(result) 函数在 console.log(result)里面打印 getValueA 功能(为什么??)
  2. this.valueAundefinedgetValueB,使我的查询无效
  3. App崩溃
  4. 我的代码出了什么问题?我应该使用另一种方法来解决这个问题吗? 提前感谢您查看:)

1 个答案:

答案 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' 
                    }
                }));
        });
    }
}