我目前正在实施一个依赖Firebase数据的应用程序,然后才能继续使用。但是,我经常(除非我故意等待)得到结果Cannot read property [property] of null
。我非常怀疑这是因为在我调用此对象之前无法进行firebase请求。
现在我正在寻找实现rendez-vous或屏障的方法,实际上是在继续之前实现接收所有firebase数据的检查点的任何方法。 Javascript中有什么可以帮助我这样做的,或者任何库,或任何反应原生的库可以帮助我实现这个目标吗?
我的代码如下所示:(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;
};
在另一个组件上,这是被调用的函数(在调用updateBookedBikeBegin()
之前收到navigateToSuccessBookedBike()
的所有数据至关重要
updateBookedBikeBegin() {
this.userStore.bookInterestedBike();
this.navigateToSuccessBookedBike();
}
答案 0 :(得分:1)
为方便起见,对于这种情况,首选使用回调承诺。您需要在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