问题
我目前正在实施一个依赖于 Firebase 数据的应用程序,然后才能继续。 但是,我经常(除非我故意等待)得到结果Cannot read property [property] of null
。 我非常怀疑这是因为在我调用这个对象之前无法发出 firebase 请求。
现在,我正在寻找实现集合点或屏障的方法,实际上是在继续之前实现接收所有 firebase 数据的检查点的任何方法。 Javascript中是否有任何东西可以帮助我做到这一点,或者任何库,或者任何可以帮助我实现这一目标的react-native库?
我的代码如下:(Fb是firebase接口)
@action
bookInterestedBike() {
this.bookedBikeNo = this.interestBikeNo;
this.downloadBikeObj();
this.updateBikeDataStartRide();
this.updateUserDataStartRide();
//
//This is where the firebase checkpoint / barrier should happen, and no progress should be made unless this data was fetched!
//
this.startTimer();
}
@action
downloadBikeObj() {
Fb.staticBikes.child(String(this.bookedBikeNo)).once('value', (bikeObj) => {
this.bikeObj = bikeObj.val();
console.log("Save object is: ");
console.log(this.bikeObj);
});
}
updateBikeDataStartRide() {
var updateVals = {}
updateVals[this.interestBikeNo] = {
bike_no: this.interestBikeNo,
current_user: "self",
positionLat: this.usrLat,
positionLng: this.usrLng
};
Fb.bikes.update(updateVals);
return false;
};
updateUserDataStartRide() {
var updateVals = {}
updateVals[this.uuid] = {
bike_no: this.bookedBikeNo,
uuid: this.uuid //TODO: remove this in deployment
};
Fb.users.update(updateVals);
return false;
};
在另一个组件上,这是调用 get 的函数(在调用navigateToSuccessBookedBike()
之前接收来自updateBookedBikeBegin()
的所有数据至关重要
updateBookedBikeBegin() {
this.userStore.bookInterestedBike();
this.navigateToSuccessBookedBike();
}
回答1
为方便起见,在这种情况下,首选使用 promise 而不是回调。 您需要在downloadBikeObj
中返回一个承诺。
downloadBikeObj() {
return Fb.staticBikes
.child(String(this.bookedBikeNo))
.once('value')
.then(bikeObj => {
this.bikeObj = bikeObj.val;
console.log("Save object is: ");
console.log(this.bikeObj);
}); // return promise
}
并在bookInterestedBike
中编写返回的承诺。
bookInterestedBike() {
this.bookedBikeNo = this.interestBikeNo;
this.downloadBikeObj()
.then(() => this.updateBikeDataStartRide())
.then(() => this.updateUserDataStartRide())
.then(() => this.startTimer());
}
参考:
https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
更多相关内容:请点击查看