为什么等待不工作等待代码完成

时间:2019-08-11 13:00:15

标签: javascript react-native firebase-realtime-database async-await

我正在尝试从firebase读取数据。但是代码是异步工作的,并且在获取数据之前先显示数据。

我已经发布了我的代码

componentDidMount(){
    var ref2 = database.ref();
    this.getItems(ref2).then((items) => {
        this.getResult(items).then((val) => {
            // why is this val coming empty 
            ToastAndroid.show(JSON.stringify(val), ToastAndroid.SHORT);
        });
    });
  }

getItems = async (ref2) => {
    var items = [];
    await ref2.once('value', snap => {
        snap.forEach((child) => {
            items.push(child.key);
        });
    });

    // this is working fine . items is correctly returned        
    return items;
}
getResult = async (items) => {
    var response = await this.getFinal(items); 
    // this response is empty why 
    return response;
}
getFinal = async (items) => {
    var result = [];
    await items.forEach((key) => {
        ref = database.ref(key);
        ref.once('value', snap => {

            snap.forEach((child) => {
                //val.push(child.val());
                var id = child.key;
                var data = {
                    username: child.val().username,
                    email: child.val().email,
                    name: child.val().name
                };
                result.push({[id]:data});    
            });
        });
    });
    // this result is empty why   
    return result;
}

我期望val不为空,结果也不为空

1 个答案:

答案 0 :(得分:1)

卢卡斯(Lukas)评论Array.forEach()不会返回承诺,因此在其上调用await并没有任何用处。

DatabaseReference.once()调用确实返回一个promise,并且由于您有多个调用,因此您可以收集promise,并等待所有这些promise完成后再返回结果:

getFinal = async (items) => {
    var promises = [],
        result = [];
    items.forEach((key) => {
        ref = database.ref(key);
        let promise = ref.once('value', snap => {
            snap.forEach((child) => {
                var id = child.key;
                var data = {
                    username: child.val().username,
                    email: child.val().email,
                    name: child.val().name
                };
                result.push({[id]:data});    
            });
        });
        promises.push(promise)
    });
    await Promise.all(promises);
    return result;
}